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操作还是涉及到高级功能如事务管理、缓存和插件的使用等。

相关推荐
编程星空4 分钟前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
程序员侠客行39 分钟前
Spring事务原理 二
java·后端·spring
sjsjsbbsbsn1 小时前
Spring Boot定时任务原理
java·spring boot·后端
计算机毕设指导62 小时前
基于Springboot学生宿舍水电信息管理系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
计算机-秋大田2 小时前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
小蒜学长3 小时前
医疗报销系统的设计与实现(代码+数据库+LW)
数据库·spring boot·学习·oracle·课程设计
羊小猪~~4 小时前
MYSQL学习笔记(九):MYSQL表的“增删改查”
数据库·笔记·后端·sql·学习·mysql·考研
豌豆花下猫4 小时前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai
橘猫云计算机设计4 小时前
基于SSM的《计算机网络》题库管理系统(源码+lw+部署文档+讲解),源码可白嫖!
java·数据库·spring boot·后端·python·计算机网络·毕设
小盼江4 小时前
水果生鲜农产品推荐系统 协同过滤余弦函数推荐水果生鲜农产品 Springboot Vue Element-UI前后端分离 代码+开发文档+视频教程
vue.js·spring boot·ui