Spring Boot整合MyBatis

/ 0

MyBatis是目前最流行的Java持久层框架,MyBatis是支持定制化SQL、存储过程已经高级映射的优秀的持久层框架。MyBatis可以对配置和原生Map使用简单的XML或注解,将接口和Java的POJO映射成数据库中的记录。摘自《深入浅出Spring Boot 2.x》。

新建Spring Boot项目

创建项目时勾选MyBatis,导入 MyBatis 库。

maven 配置文件 pom.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>springboot</groupId>
    <artifactId>chapter6</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>chapter6</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

测试表

创建一个数据库,并新建一张 t_user 测试表,用于演示。

CREATE TABLE `t_user` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(60) NOT NULL,
  `note` varchar(512) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

POJO和Mapper

User.java 对应数据库中 t_user 表的POJO对象:

@Alias("user") // 别名,可以在mapper映射配置文件中使用
public class User {
    private Long id;
    private String userName;
    private String note;
    /* getter and setter... */
}

UserMapper.java 接口文件:

@Mapper
public interface UserMapper {

    User getUser(Long id);

    int insertUser(User user);
}

UserMapper.xml 映射配置文件:

<?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="com.springboot.chapter6.mapper.UserMapper">
    <!-- 根据用户编号查询用户,这里的user就是我们前面定义的别名 -->
    <select id="getUser" parameterType="long" resultType="user">
        select id, user_name as userName, note
        from t_user
        where id = #{id}
    </select>
    <!-- 新增用户 -->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(user_name, note)
        values (#{userName}, #{note})
    </insert>
</mapper>

编写业务逻辑

UserService.java 用户服务接口:

public interface UserService {

    User getUser(Long id);

    int insertUser(User user);
}

UserServiceImpl.java 用户服务接口实现类:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUser(Long id) {
        return userMapper.getUser(id);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }
}

UserController.java 用户控制器:

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser(Long id) {
        return userService.getUser(id);
    }

    @RequestMapping("/insertUser")
    @ResponseBody
    public Map<String, Object> insertUser(String userName, String note) {
        User user = new User();
        user.setUserName(userName);
        user.setNote(note);

        // 结果会回填主键,返回插入条数
        int update = userService.insertUser(user);
        Map<String, Object> result = new HashMap<>();
        result.put("success", update == 1);
        result.put("user", user);
        return result;
    }

}

配置MyBatis

在启动类中配置 MyBatis 扫描 Mapper 接口的基础包名,并限定了只扫描 Mapper 注解类型,这样就可以把 MyBatis 对应的 Mapper 接口的实例扫描到 Spring IoC 容器中了。

Application.java Spring Boot启动类:

@SpringBootApplication
@MapperScan(basePackages = "com.springboot.test", annotationClass = Mapper.class) 
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

application.properties 项目配置文件,配置数据连接信息、 MyBatis 的 Mapper 映射配置文件和 POJO 中的类型别名包路径。

# 数据库连接信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/chapter6?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

# MyBatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.springboot.test.pojo

测试结果

新增用户
查询用户