spring boot 整合 mybatis

spring boot jpa的方式确实非常简单, 但是复杂系统避免不了自己写sql, 那么如果把sql写在方法的上面, 可能有些人会觉得怪异, 或者不舒服.

那么能不能将mybatis整合进spring boot , 将sql 分离出来呢.

一. pom.xml

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

引入mybatis starter 的jar包, 这里不再需要引入mybatis的其他jar包了. 包含在里面

 

二. yml配置文件

mybatis:
  mapper-locations: classpath:mapper/**/*.xml

这里配置一下, mapper.xml文件存放位置

 

三. mapper类扫描配置

@MapperScan("org.elvin.boot.mapper")
@SpringBootApplication
public class BootApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }
}

在boot启动程序上, 加一个注解, 扫描mapper类文件

 

四. mapper文件

package org.elvin.boot.mapper;

import org.elvin.boot.pojo.db.User;

import java.util.List;

/**
 * author: Elvin
 * Date: 2017/12/7 15:29
 * Description:
 */
public interface UserMapper {

    public List<User> findAll();

}

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.elvin.boot.mapper.UserMapper">

    <select id="findAll" resultType="org.elvin.boot.pojo.db.User">
      select id, name, birthday  from user
    </select>

</mapper>

  

五. service 和实现类

/**
 * author: Elvin
 * Date: 2017/12/7 15:36
 * Description:
 */
public interface UserService {

    public List<User> findAll();
}
/**
 * author: Elvin
 * Date: 2017/12/7 15:36
 * Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }
}

 

六. controller

/**
 * author: Elvin
 * Date: 2017/12/7 15:39
 * Description:
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("all")
    public List<User> all(){
        return userService.findAll();
    }
}

 

七. 结果

这样子, 功能上, 和之前 ssm(2) 整合的差不多了

 

posted @ 2017-12-09 11:38  Sniper_ZL  阅读(1038)  评论(0编辑  收藏  举报