Spring Boot 中集成 MyBatis

10.1 MyBatis 介绍

大家都知道,MyBatis 框架是一个持久层框架,是 Apache 下的顶级项目。Mybatis 可以让开发者把主要精力放在 SQL 上,通过 Mybatis 提供的映射方式,自由灵活地生成满足需要的 SQL 语句。使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs 映射成数据库中的记录,在国内可谓是占据了半壁江山。

本节课将讲解 Spring Boot 集成 MyBatis 的两种方式,重点讲解基于注解的方式。该方式更为简洁,省去了很多 XML 的配置过程,所以在实际项目中也较常使用。当然这也不是绝对的,有些项目组中也在使用 XML 方式。

10.2 MyBatis 的配置

10.2.1 依赖导入

Spring Boot 集成 MyBatis,需要导入 mybatis-spring-boot-starter 和 MySQL 的依赖,这里我们使用的版本是 1.3.2,代码如下:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

我们点开 mybatis-spring-boot-starter 依赖,可以看到很多之前使用过、较为熟悉的依赖,就像课程开始介绍的那样,Spring Boot 致力于简化编码,使用 starter 系列将相关依赖集成在一起,开发者不需要关注繁琐的配置,非常方便。

org.mybatis mybatis org.mybatis mybatis-spring
10.2.2 properties.yml 配置

我们再来看一下,集成 MyBatis 时需要在 properties.yml 配置文件中做哪些基本配置,代码如下:

# 服务端口号
server:
  port: 8080

# 数据库地址
datasource:
  url: localhost:3306/blog_test

spring:
  datasource: # 数据库配置
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://${datasource.url}?useSSL=false&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&maxReconnects=10
    username: root
    password: 123456
    hikari:
      maximum-pool-size: 10 # 最大连接池数
      max-lifetime: 1770000

mybatis:
  # 指定别名设置的包为所有entity
  type-aliases-package: com.itcodai.course10.entity
  configuration:
    map-underscore-to-camel-case: true # 驼峰命名规范
  mapper-locations: # mapper 映射文件位置
    - classpath:mapper/*.xml

我们简单介绍下上面这些配置。

数据库的相关配置,这里就不详细解说了,相信大家已经非常熟练了,主要是配置用户名、密码、数据库连接等,本节课使用的连接池是 Spring Boot 自带的 Hikari,感兴趣的朋友可以去百度或者谷歌搜索,了解一下。

这里着重说明一下 map-underscore-to-camel-case:true, 它用来开启驼峰命名规范,比较好用,比如数据库中字段名为 user_name, 那么在实体类中定义名为 userName 的属性,甚至是 username,都会自动匹配到驼峰属性。如果不这样配置,当字段名和属性名不同时,就无法实现映射。

10.3 基于 XML 的整合

使用原始的 XML 方式,需要新建 UserMapper.xml 文件。在上面的 application.yml 配置文件中,我们已经定义了 XML 文件的路径:classpath:mapper/*.xml,接下来我们在 resources 目录下新建一个 mapper 文件夹,然后创建一个 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.itcodai.course10.dao.UserMapper">
  <resultMap id="BaseResultMap" type="com.itcodai.course10.entity.User">

    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>

   <select id="getUserByName" resultType="User" parameterType="String">
       select * from user where user_name = #{username}
  </select>
</mapper>

这和整合 Spring 一样,namespace 中指定的是对应的 Mapper, 中指定对应的实体类,即 User,在内部指定表的字段和实体的属性相对应即可。这里我们写一个根据用户名查询用户的 SQL。

实体类中有 id、username 和 password,我不在这贴代码,大家可以下载源码查看。UserMapper.java 文件中写一个接口即可:

User getUserByName(String username);

中间省略了 service 的代码,我们写一个 Controller 来测试一下:

@RestController
public class TestController {

    @Resource
    private UserService userService;

    @RequestMapping("/getUserByName/{name}")
    public User getUserByName(@PathVariable String name) {
        return userService.getUserByName(name);
    }
}

启动项目,在浏览器中输入:http://localhost:8080/getUserByName/CSDN 即可查询到数据库表中用户名为 CSDN 的用户信息(事先放两个数据进去即可):

{"id":2,"username":"CSDN","password":"123456"}

这里需要注意一下:Spring Boot 是如何知道这个 Mapper 的呢?一种方法是在 mapper 层对应的类上添加 @Mapper 注解即可,但这种方法有个弊端,当我们有很多个 mapper 时,每一个类上都得添加 @Mapper 注解。另一种比较简便的方法是在 Spring Boot 启动类上添加 @MaperScan 注解,用来扫描某个包下的所有 mapper。代码如下:

@SpringBootApplication
@MapperScan("com.itcodai.course10.dao")
public class Course10Application {

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

}
这样的话,com.itcodai.course10.dao 包下的所有 mapper 都会被扫描到了。

10.4 基于注解的整合

基于注解的整合就不需要 XML 配置文件了,MyBatis 主要提供了 @Select 、@Insert、@Update、Delete 四个注解。这四个注解用得比较多,也很简单,注解后面跟上对应的 SQL 语句即可,我们举个例子:

@Select("select * from user where id = #{id}")
User getUser(Long id);

这与 XML 文件中写 SQL 语句是一样的,不再需要 XML 文件。有人可能会问,如果是两个参数呢?两个参数的话,我们需要使用 @Param 注解来指定每一个参数的对应关系,如下:

@Select("select * from user where id = #{id} and user_name=#{name}")
User getUserByIdAndName(@Param("id") Long id, @Param("name") String username);

可以看出,@Param 指定的参数要和 SQL 中 #{} 取的参数名相同,不同则取不到。可以在 Controller 中自行测试一下,接口都在源码中,文章中就不再粘贴测试代码和结果了。

有个问题请大家注意:表字段设计完成后,我们多会使用自动生成工具生成实体类,这时实体类的名称要与表字段的名称相对应,最起码也要符合驼峰对应。上面实例中,我们在配置文件中开启了驼峰的配置,所以字段都能很好地相对应。万一有对不上的呢?我们也有解决办法,即使用 @Results 注解。

@Select("select * from user where id = #{id}")
@Results({
        @Result(property = "username", column = "user_name"),
        @Result(property = "password", column = "password")
})
User getUser(Long id);

@Results 中的 @Result 注解用来指定每一个属性和字段的对应关系,这样就解决了该问题

当然,我们也可以将 XML 和注解结合使用,实际项目中也多采用混用的方式。因为有时采用 XML 方式方便,有时候则使用注解方式更方便,比如上面这个问题,如果我们定义了上面的 UserMapper.xml,则完全可以使用 @ResultMap 注解来替代 @Results 注解,如下:

@Select("select * from user where id = #{id}")
@ResultMap("BaseResultMap")
User getUser(Long id);

@ResultMap 注解中的值来自哪里呢?对应的是 UserMapper.xml 文件中 的 id 属性值,如下:

<resultMap id="BaseResultMap" type="com.itcodai.course10.entity.User">

XML 和注解结合使用的情况很常见,借助自动生成工具生成 XML 文件,更是减少了大量的代码,也省去了人为手动输入。

猜你喜欢

转载自blog.csdn.net/taojin12/article/details/88314548