Spring Boot 整合 Mybatis

2021-08-26  本文已影响0人  葱大驴

资料 mybatis 官网: Mybatis

1 导入依赖

mybatis 的 spring boot start 依赖

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

Mybatis 的 starter 主要提供了这些功能

  1. 检测DataSource
    自动检测项目中已经存在的 DataSource 对象
  2. 生成并注册 SqlSessionFactory
    通过 SqlSessionFactoryBean 生成并注册一个 SqlSessionFactory 对象,并且传入 1 里面的 DataSource 作为参数
  3. 创建并注册SqlSessionTemplate
    在SqlSessionFactory 之外
  4. 扫描 Mapper
    他会
    - 自动扫描你的 mappers 并连接到 SqlSessionTemplate
    - 将 mappers 注册到 Spring context 中,以便你随时注入

2 配置Data Source (数据源)

配置Spring自带的 DataSource

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/数据库?serverTimezone=UTC
    username: 帐号
    password: 密码
    ## 使用 Mysql 驱动,确保引入了 mysql-connection 的依赖
    driver-class-name: com.mysql.cj.jdbc.Driver

3 使用 MyBatis

在完成 MyBatis 和 Data source 的配置之后,就可以开始使用 Mybatis了
方法一 全注解

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM USER")
    List<UserDao> getUsers();

    @Select("Select * FROM USER WHERE user_id = #{userId}")
    UserDao getUserByUserId(@Param("userId") int userId);
}
@RestController
@RequestMapping("user")
public class UserController {
    private UserMapper userMapper;
     // 这里会有编译警告,因为 mapper不是由Spring主动注册为bean的,
    // 而是由 mybatis starter做的
    public UserController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @GetMapping("/getUsers")
    public ResponseEntity getUsers() {
        return ResponseEntity.ok(userMapper.getUsers());
    }
}

方法二,自动扫描
方法一简单易懂,但是如果涉及到大量的数据库操作,一个个mapper去写注释就会显得有点傻,这时可以用一个 @MapperScan 注解,就可以去掉每个 mapper 的@Mapper 注解(就这?)

@SpringBootApplication
@MapperScan("com.org.test.mapper")
public class TestApplication {
    private static ApplicationContext applicationContext;
    ...
}

方法三, 使用 SqlSession
SqlSession 的用法可以参照 Mybatis 的官方教程 Mybatis 教程

方法四, 使用 mapper xml
使用 Mybatis 的 xml 直接写 SQL

  1. 在配置文件中指定两个属性
  # resource 底下放置 mapper xml 的路径
  mapper-locations: classpath*:mapper/*.xml
  # POJO 类所在的目录
  type-aliases-package: com.org.test.domain
  1. 加上 @MapperScan(basePackages = "com.org.test.mapper")
    注意:在 spring boot 之前, mybatis整合 spring 需要配置一个mybatis文件,在文件中配置mybatis的配置(如自动扫描)等。但在Spring boot中,由于mybatis-starter默认接管了这部分的配置,因此不再需要了,如果还想要这份配置文件,就不能再用spring配置文件配置mybatis任何配置,否则会报一个冲突错误
Property 'configuration' and 'configLocation' can not specified with together
  1. 写 Domain 和 Mapper 接口
public interface UserMapper {
    List<User> getUsers();
    UserDao getUserByUserId(Integer userId);
}
  1. 配置 xml
    在 1 中配置的目录下创建 mapper文件
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.org.auth.mapper.UserMapper">
    <resultMap id="UserResultMap" type="User">
        <id column="user_id" property="userId" />
        <result column="name" property="name" />
        <result column="gender" property="gender" />
        <result column="dept_id" property="deptId" />
    </resultMap>

    <select id="getUsers" resultMap="UserResultMap">
        SELECT * FROM user;
    </select>

    <select id="getUserByUserId" resultMap="UserResultMap">
        SELECT * FROM user where user_id = #{userId};
    </select>
</mapper>
上一篇下一篇

猜你喜欢

热点阅读