SpringBoot整合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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值