Spring Boot与MyBatis

Spring Boot与MyBatis的配置

一、简介

Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架,它简化了Spring应用的初始搭建以及开发过程。MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。将Spring Boot和MyBatis结合使用,可以高效地开发数据驱动的应用程序。

二、环境准备

(一)创建Spring Boot项目
  1. 可以使用Spring Initializr(https://start.spring.io/)来创建一个基础的Spring Boot项目。
    • 在创建项目时,选择合适的项目元数据,如项目的Group和Artifact等信息。
    • 可以选择添加一些常用的依赖,如Web依赖(如果项目需要提供Web服务)等。不过,对于MyBatis的集成,初始创建时不需要专门添加MyBatis相关依赖,我们后续手动添加。
  2. 下载生成的项目压缩包并解压到本地开发环境。
(二)添加MyBatis依赖
  1. 在项目的pom.xml(如果是Maven项目)中添加MyBatis和相关数据库驱动的依赖。
    • 对于MyBatis本身:

      复制代码
      <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis - spring - boot - starter</artifactId>
          <version>2.2.2</version>
      </dependency>
    • 如果使用MySQL数据库,添加MySQL驱动依赖:

      复制代码
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql - connector - java</artifactId>
          <version>8.0.26</version>
      </dependency>

三、数据库配置

(一)配置数据源
  1. 在Spring Boot的配置文件(application.properties或者application.yml)中配置数据源相关信息。
    • 如果使用application.properties:

      复制代码
      spring.datasource.url = jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTC
      spring.datasource.username = root
      spring.datasource.password = your_password
      spring.datasource.driver - class - name = com.mysql.cj.jdbc.Driver
    • 如果使用application.yml:

      复制代码
      spring:
        datasource:
          url: jdbc:mysql://localhost:3306/mydb?useSSL = false&serverTimezone = UTC
          username: root
          password: your_password
          driver - class - name: com.mysql.cj.jdbc.Driver

四、MyBatis配置

(一)实体类创建
  1. 根据数据库表结构创建对应的实体类。例如,如果有一个名为"user"的表,结构如下:

    复制代码
    CREATE TABLE user (
        id INT PRIMARY KEY AUTO_INCREMENT,
        username VARCHAR(50),
        password VARCHAR(50)
    );
    • 对应的Java实体类为:

      复制代码
      public class User {
          private Integer id;
          private String username;
          private String password;
          // 生成getter和setter方法
          public Integer getId() {
              return id;
          }
          public void setId(Integer id) {
              this.id = id;
          }
          public String getUsername() {
              return username;
          }
          public void setUsername(String username) {
              this.username = username;
          }
          public String getPassword() {
              return password;
          }
          public void setPassword(String password) {
              this.password = password;
          }
      }
(二)Mapper接口创建
  1. 创建Mapper接口来定义与数据库交互的方法。
    • 例如,创建一个UserMapper接口:

      复制代码
      @Mapper
      public interface UserMapper {
          User selectUserById(Integer id);
          int insertUser(User user);
          int updateUser(User user);
          int deleteUserById(Integer id);
      }
    • 这里的@Mapper注解(如果使用注解方式)用于将该接口标记为MyBatis的Mapper接口,这样Spring Boot就能够识别并自动创建该接口的代理实现。

(三)Mapper XML文件创建(如果使用XML方式)
  1. 如果不使用注解方式编写SQL语句,而是使用XML文件,则需要创建Mapper XML文件。
    • 在resources/mapper目录下创建UserMapper.xml(假设项目采用的是Maven的标准目录结构)。

    • 内容如下:

      复制代码
      <?xml version="1.0" encoding="UTF - 8"?>
      <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis - 3.dtd">
      <mapper namespace="com.example.demo.mapper.UserMapper">
          <select id="selectUserById" resultMap="userResultMap">
              SELECT * FROM user WHERE id = #{id}
          </select>
          <insert id="insertUser">
              INSERT INTO user (username, password) VALUES (#{username}, #{password})
          </insert>
          <update id="updateUser">
              UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
          </update>
          <delete id="deleteUserById">
              DELETE FROM user WHERE id = #{id}
          </delete>
          <resultMap id="userResultMap" type="com.example.demo.entity.User">
              <id property="id" column="id"/>
              <result property="username" column="username"/>
              <result property="password" column="password"/>
          </resultMap>
      </mapper>
    • 这里的namespace属性的值要与对应的Mapper接口的全限定名相同。

(四)配置MyBatis扫描路径
  1. 如果使用XML方式的Mapper文件,需要在Spring Boot配置文件中配置MyBatis的Mapper扫描路径。
    • 在application.properties中:

      复制代码
      mybatis.mapper - locations = classpath:mapper/*.xml
    • 在application.yml中:

      复制代码
      mybatis:
        mapper - locations: classpath:mapper/*.xml

五、使用MyBatis进行数据操作

(一)在Service层调用Mapper方法
  1. 创建一个UserService类来调用UserMapper中的方法。
    • 例如:

      复制代码
      @Service
      public class UserService {
          @Autowired
          private UserMapper userMapper;
          public User getUserById(Integer id) {
              return userMapper.selectUserById(id);
          }
          public int addUser(User user) {
              return userMapper.insertUser(user);
          }
          public int updateUserInfo(User user) {
              return userMapper.updateUser(user);
          }
          public int deleteUser(int id) {
              return userMapper.deleteUserById(id);
          }
      }
    • 这里通过@Autowired注解注入UserMapper实例,然后就可以在Service方法中调用Mapper中的数据操作方法。

(二)在Controller层调用Service方法(如果是Web应用)
  1. 创建一个UserController类(假设是一个Web应用,需要提供RESTful接口等)。

    复制代码
    @RestController
    public class UserController {
        @Autowired
        private UserService userService;
        @GetMapping("/user/{id}")
        public User getUserById(@PathVariable("id") Integer id) {
            return userService.getUserById(id);
        }
        @PostMapping("/user")
        public int addUser(@RequestBody User user) {
            return userService.addUser(user);
        }
        @PutMapping("/user")
        public int updateUser(@RequestBody User user) {
            return userService.updateUserInfo(user);
        }
        @DeleteMapping("/user/{id}")
        public int deleteUser(@PathVariable("id") Integer id) {
            return userService.deleteUser(id);
        }
    }
    • 这里同样通过@Autowired注解注入UserService实例,然后在Controller的各个方法中调用Service方法,实现了从Web请求到数据操作的完整流程。

六、事务管理

  1. 在Spring Boot中管理MyBatis的事务非常方便。
    • 如果要在某个Service方法上添加事务管理,可以使用@Transactional注解。例如:

      复制代码
      @Service
      public class UserService {
          @Autowired
          private UserMapper userMapper;
          @Transactional
          public int addUser(User user) {
              // 一些业务逻辑判断等操作
              int result = userMapper.insertUser(user);
              // 如果插入成功后还有其他操作,如更新相关联的数据等
              return result;
          }
      }
    • 这样,如果在addUser方法中的任何一个数据库操作出现异常,整个事务都会回滚,保证数据的一致性。

七、高级配置

(一)配置MyBatis的缓存
  1. MyBatis提供了一级缓存和二级缓存。
    • 一级缓存是基于SqlSession的,默认是开启的。

    • 二级缓存可以通过在Mapper接口或者Mapper XML文件中配置开启。

    • 在Mapper XML文件中配置二级缓存:

      复制代码
      <?xml version="1.0" encoding="UTF - 8"?>
      <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis - 3.dtd">
      <mapper namespace="com.example.demo.mapper.UserMapper">
          <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
          <!-- 其他SQL语句定义等 -->
      </mapper>
    • 这里的标签用于配置二级缓存的相关属性,如缓存的清除策略(eviction)、刷新间隔(flushInterval)、缓存大小(size)和是否只读(readOnly)等。

(二)配置MyBatis的插件
  1. MyBatis允许使用插件来扩展其功能。例如,可以使用PageHelper插件来实现分页功能。
    • 首先添加PageHelper的依赖:

      复制代码
      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper - spring - boot - starter</artifactId>
          <version>1.3.0</version>
      </dependency>
    • 然后在配置文件中进行简单配置(以application.yml为例):

      复制代码
      pagehelper:
        helper - dialect: mysql
        reasonable: true
        support - methods - arguments: true
    • 在使用分页查询时,在Mapper接口方法调用之前使用PageHelper.startPage方法即可。例如:

      复制代码
      public class UserService {
          @Autowired
          private UserMapper userMapper;
          public List<User> getUsersByPage(int pageNum, int pageSize) {
              PageHelper.startPage(pageNum, pageSize);
              return userMapper.selectAllUsers();
          }
      }

通过以上的配置和操作步骤,就可以在Spring Boot项目中成功地集成和使用MyBatis进行高效的数据持久化操作,无论是简单的CRUD操作还是涉及到高级功能如事务管理、缓存和插件的使用等。

相关推荐
李昊哲小课1 小时前
Spring Boot SSE 实时推送教程
spring boot·websocket·flux·sseemitter
狗头大军之江苏分军2 小时前
《潮水漫过十七岁》开学了
后端
苏三说技术2 小时前
如何看待GPT-6在UP主众测中碾压夺冠?它是现在最强大模型吗?
后端
mldong2 小时前
一份 JSON,一条能跑的审批流:把报销流程送上工作流引擎
后端·架构
wno7042 小时前
Spring Boot WebFlux增删改查
java·spring boot·后端
Captaincc2 小时前
AI用量v0.1.11更新发布 新增 jusage doctor 诊断指令 托盘展示token 和余额 新增 AutoClaw 支持
前端·后端·vibecoding
aramae3 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端
行百里er5 小时前
Spring Insight 里如何把 Span 收成一条链路
spring boot·spring cloud·监控
IT_陈寒5 小时前
Python的GIL把我坑惨了,多线程跑得比单线程还慢
前端·人工智能·后端
分支预测失败5 小时前
RISC-V 时间子系统深度专题:mtime 访问路径、SBI 定时器与 Linux tickless 协同
后端