java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot与MyBatis配置

Spring Boot与MyBatis配置与操作实战指南

作者:ljbguanli

本文介绍了如何在SpringBoot项目中配置和使用MyBatis,包括环境准备、数据源配置、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依赖

在项目的pom.xml(如果是Maven项目)中添加MyBatis和相关数据库驱动的依赖。

对于MyBatis本身:  ​​​​​

 org.mybatis.spring.boot
    mybatis - spring - boot - starter
    2.2.2

如果使用MySQL数据库,添加MySQL驱动依赖:    ​​​​​​

mysql
    mysql - connector - java
    8.0.26

三、数据库配置

(一)配置数据源

在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配置

(一)实体类创建

根据数据库表结构创建对应的实体类。例如,如果有一个名为“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接口创建

创建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方式)

如果不使用注解方式编写SQL语句,而是使用XML文件,则需要创建Mapper XML文件。

在resources/mapper目录下创建UserMapper.xml(假设项目采用的是Maven的标准目录结构)。

内容如下:

SELECT * FROM user WHERE id = #{id}
        INSERT INTO user (username, password) VALUES (#{username}, #{password})
        UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}
        DELETE FROM user WHERE id = #{id}

这里的namespace属性的值要与对应的Mapper接口的全限定名相同。

(四)配置MyBatis扫描路径

如果使用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方法

创建一个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应用)

创建一个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请求到数据操作的完整流程。

六、事务管理

在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提供了一级缓存和二级缓存。
    1. 一级缓存是基于SqlSession的,默认是开启的。
    2. 二级缓存可以通过在Mapper接口或者Mapper XML文件中配置开启。
    3. 在Mapper XML文件中配置二级缓存:

(二)配置MyBatis的插件

MyBatis允许使用插件来扩展其功能。例如,可以使用PageHelper插件来实现分页功能。

首先添加PageHelper的依赖:

 com.github.pagehelper
    pagehelper - spring - boot - starter
    1.3.0

然后在配置文件中进行简单配置(以application.yml为例):

pagehelper:
  helper - dialect: mysql
  reasonable: true
  support - methods - arguments: true

在使用分页查询时,在Mapper接口方法调用之前使用PageHelper.startPage方法即可。例如:

public class UserService {
    @Autowired
    private UserMapper userMapper;
    public List getUsersByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.selectAllUsers();
    }
}

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

到此这篇关于Spring Boot与MyBatis配置与操作实战指南的文章就介绍到这了,更多相关Spring Boot与MyBatis配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文