SpringBoot集成MyBatis

目录

实现步骤

1. 在项目的 pom.xml 配置文件中引入如下依赖

2. 在项目的 application.properties 配置文件中添加如下依赖

3. 新建 UserMapper.class 接口类,添加如下 3 个方法

4. 在 /resources/mybatis/mapper 路径(需要手动创建文件夹)下创建 UserMapper.xml 文件,添加如下操作数据库配置

5. 省略 UserService.class/UserServiceImpl.class 类代码,创建 UserController.class 并添加如下代码测试

补充


实现步骤

1. 在项目的 pom.xml 配置文件中引入如下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

注意:这里我们没有引入其他的数据源,所以引入 spring-boot-starter-data-jdbc 依赖,使用 Hikari 数据源,如果要使用其他的数据源,则需要引入对应依赖即可

2. 在项目的 application.properties 配置文件中添加如下依赖

#################### 数据库连接池配置 ####################
# 数据库连接地址
spring.datasource.url = jdbc:mysql://localhost:3306/spring_study?characterEncoding=utf8&serverTimezone=UTC
# 数据库驱动类
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
# 数据库用户名
spring.datasource.username = root
# 数据库密码
spring.datasource.password = dufu9137*
# 最小空闲连接
spring.datasource.hikari.minimum-idle = 2
# 最大连接数
spring.datasource.hikari.maximum-pool-size = 3
# 连接最大存活时间(应大于等于 30000)
spring.datasource.hikari.max-lifetime = 30000
# 空闲连接超时时间(应小于 max-lifetime 的值)
spring.datasource.hikari.idle-timeout = 20000
# 用于测试连接是否可用的查询语句
spring.datasource.hikari.connection-test-query = SELECT 1

#################### MyBatis 配置 ####################
# 指定 Mapper.xml 文件的位置
mybatis.mapper-locations = classpath:mybatis/mapper/*.xml
# 开启驼峰命名映射规则
mybatis.configuration.map-underscore-to-camel-case = true
# 打开日志输出功能
mybatis.configuration.log-impl = org.apache.ibatis.logging.stdout.StdOutImpl
# 设置实体类映射别名所在包路径
mybatis.type-aliases-package = com.study.springboot.entities
# 设置操作超时时间
mybatis.configuration.default-statement-timeout = 3
# 开启缓存
mybatis.configuration.cache-enabled = true

3. 新建 UserMapper.class 接口类,添加如下 3 个方法

@Mapper
public interface UserMapper {
    User getUserById(Integer id);
    List<User> getUserList();
    Integer addUser(User user);
}

4. 在 /resources/mybatis/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.study.springboot.mapper.UserMapper">
    <select id="getUserById" parameterType="int" resultType="User">
      select * from user where id = #{id}
    </select>
    <select id="getUserList" resultType="User">
      select * from user order by id asc
    </select>
    <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
      insert into user(name) values(#{name})
    </insert>
</mapper>

5. 省略 UserService.class/UserServiceImpl.class 类代码,创建 UserController.class 并添加如下代码测试

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/byId")
    public User getUserById(@RequestParam Integer id) {
        return userService.getUserById(id);
    }

    @GetMapping("/list")
    public List<User> getUserList() {
        return userService.getUserList();
    }

    @PostMapping("/add")
    public User addUser(@RequestBody User user) {
        Integer count = userService.addUser(user);
        return count == 1 ? user : null;
    }
}

补充

1. xxxMapper.class 上添加 @Mapper 注解表明这是一个 Mapper 类,也可以在项目启动类或添加了 @Configuration 注解的配置类上添加 @MapperScan("com.study.springboot.mapper") 注解表明这个包路径下的所有接口类都是 Mapper 类;但建议使用 @Mapper 注解实现

2. 我们这里使用的 xxxMapper.xml 配置文件的方式添加 SQL 语句操作数据库,也可以在 xxxMapper.class 类上直接使用 @Select、@Update、@Insert、@Delete 注解直接添加 SQL 语句操作;注意注解式添加 SQL,方法中的参数可能需要 @Param 注解标记

3. 对于自增的记录,有时候我们需要插入操作后直接返回插入的结果,但是得不到自增的主键,如果是使用 xxxMapper.xml 文件方式,可以通过添加如下属性解决这个问题

<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
  insert into user(name) values(#{name})
</insert>

如果是使用注解的方式,那么可通过添加 @Options 注解添加属性解决这个问题

@Insert("insert into user(name) values(#{name})")
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
Integer addUser(User user);

useGeneratedKeys = true,表示使用自增主键

keyColumn = "id",数据库中主键列名

keyProperty = "id",映射实体类主键字段

4. MyBatis 操作数据库时,传递的参数为对象的话,在 SQL 语句中,直接使用对象的属性占位即可,例如

@Insert("insert into user(name) values(#{name})")
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
Integer addUser(User user);

如果参数使用了 @Param 注解的话,则需要使用 @Param 注解的值.对象属性占位,例如

@Insert("insert into user(name) values(#{user.name})")
@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
Integer addUser(@Param("user") User user);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值