Spring?Boot?集成?MyBatis?全面講解(最新推薦)
Spring Boot 集成 MyBatis 全面講解
MyBatis 是一款優(yōu)秀的持久層框架,與 Spring Boot 集成后可以大大簡化開發(fā)流程。本文將全面講解如何在 Spring Boot 中集成 MyBatis,包括環(huán)境配置、基礎(chǔ)操作、高級功能和最佳實踐。
一、MyBatis 簡介
1. SqlSession
SqlSession 是 MyBatis 的核心接口,負(fù)責(zé)執(zhí)行 SQL 語句、獲取映射器實例以及管理事務(wù)。
1.1 SqlSession 的創(chuàng)建
SqlSession 通常通過 SqlSessionFactory 獲取。以下是創(chuàng)建 SqlSessionFactory 的典型代碼:
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
// 使用 session 進行數(shù)據(jù)庫操作
}注意:在 Spring 集成中,
SqlSessionFactory和SqlSession的創(chuàng)建由框架管理,我們只需要通過依賴注入獲取即可。
1.2 SqlSession 的常用方法
SqlSession 提供了多種方法,用于執(zhí)行數(shù)據(jù)庫操作:
查詢操作:
// 單條記錄查詢
User user = session.selectOne("namespace.statementId", parameter);
// 多條記錄查詢
List<User> users = session.selectList("namespace.statementId", parameter);
插入操作:
int rows = session.insert("namespace.statementId", parameter);更新操作:
int rows = session.update("namespace.statementId", parameter);刪除操作:
int rows = session.delete("namespace.statementId", parameter);事務(wù)控制:
session.commit(); // 提交事務(wù)session.rollback(); // 回滾事務(wù)
2. Mapper 映射器
Mapper 映射器是 MyBatis 的核心功能,用于實現(xiàn) SQL 和 Java 方法之間的映射。它可以通過注解或 XML 配置。
2.1 基于注解的 Mapper
注解方式直接將 SQL 寫在 Mapper 接口中,簡單高效,適合簡單場景。
示例代碼:
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User selectById(Long id);
@Insert("INSERT INTO user (username, email) VALUES (#{username}, #{email})")
int insertUser(User user);
@Update("UPDATE user SET email = #{email} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(Long id);
}2.2 基于 XML 的 Mapper
XML 配置更加靈活,適合復(fù)雜查詢場景。Mapper XML 文件通常位于 resources/mapper 目錄。
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-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<!-- 查詢 -->
<select id="selectById" parameterType="long" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 插入 -->
<insert id="insertUser" parameterType="com.example.entity.User">
INSERT INTO user (username, email)
VALUES (#{username}, #{email})
</insert>
<!-- 更新 -->
<update id="updateUser" parameterType="com.example.entity.User">
UPDATE user SET email = #{email} WHERE id = #{id}
</update>
<!-- 刪除 -->
<delete id="deleteUser" parameterType="long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>2.3 Mapper 映射器的工作機制
Mapper 接口的方法名和參數(shù)需要與 XML 中的 id 和 parameterType 對應(yīng)。MyBatis 會通過動態(tài)代理為 Mapper 接口生成實現(xiàn)類,并調(diào)用對應(yīng)的 SQL。
3. 配置文件
MyBatis 的配置文件包括全局配置文件(mybatis-config.xml)和映射文件(mapper.xml)。
3.1 全局配置文件
mybatis-config.xml 定義了數(shù)據(jù)庫連接、日志設(shè)置、別名等全局配置。
典型配置示例:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 環(huán)境配置 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 別名配置 -->
<typeAliases>
<typeAlias type="com.example.entity.User" alias="User"/>
</typeAliases>
<!-- Mapper 映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>3.2 映射文件配置
映射文件定義了具體的 SQL 和 Java 對象之間的關(guān)系。以 UserMapper.xml 為例:
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectAll" resultType="User">
SELECT * FROM user
</select>
<resultMap id="UserResultMap" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="email" property="email"/>
</resultMap>
</mapper>4. ResultMap
ResultMap 是 MyBatis 的強大特性之一,用于處理復(fù)雜查詢結(jié)果與 Java 對象的映射關(guān)系。
4.1 什么是 ResultMap?
ResultMap 用于自定義數(shù)據(jù)庫字段與 Java 對象屬性的映射。它支持嵌套映射、別名和字段處理,適合復(fù)雜的對象映射場景。
4.2 ResultMap 配置示例
以下是一個帶嵌套對象的 ResultMap 配置:
數(shù)據(jù)庫表:
CREATE TABLE user (
id BIGINT PRIMARY KEY,
username VARCHAR(50),
email VARCHAR(100)
);
CREATE TABLE address (
id BIGINT PRIMARY KEY,
user_id BIGINT,
city VARCHAR(50),
FOREIGN KEY (user_id) REFERENCES user(id)
);Java 對象:
@Data
public class User {
private Long id;
private String username;
private String email;
private Address address;
}
@Data
public class Address {
private Long id;
private String city;
}ResultMap 配置:
<resultMap id="UserWithAddress" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="email" property="email"/>
<association property="address" javaType="Address">
<id column="address_id" property="id"/>
<result column="city" property="city"/>
</association>
</resultMap>查詢語句:
<select id="getUserWithAddress" resultMap="UserWithAddress">
SELECT u.id, u.username, u.email, a.id AS address_id, a.city
FROM user u
LEFT JOIN address a ON u.id = a.user_id
WHERE u.id = #{id}
</select>4.3 嵌套集合映射
對于一對多的嵌套關(guān)系,可以使用 <collection>:
<resultMap id="UserWithPosts" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<collection property="posts" ofType="Post">
<id column="post_id" property="id"/>
<result column="title" property="title"/>
</collection>
</resultMap>總結(jié)
SqlSession、Mapper、配置文件 和 ResultMap 是 MyBatis 的核心概念。通過靈活的配置和映射,MyBatis 可以高效地處理各種復(fù)雜的數(shù)據(jù)庫操作需求。熟練掌握這些特性可以讓開發(fā)者在項目中更高效地處理數(shù)據(jù)訪問邏輯。
三、Spring Boot 集成 MyBatis
MyBatis 是一種輕量級的持久層框架,與 Spring Boot 集成后可以極大地提升開發(fā)效率。以下是集成的完整步驟,包括項目配置、數(shù)據(jù)庫設(shè)計和基本操作。
1. 創(chuàng)建 Spring Boot 項目
在創(chuàng)建項目時,可以使用 Spring Initializr 快速生成骨架項目。以下依賴是集成 MyBatis 所必需的:
- Spring Web:用于創(chuàng)建 REST API。
- MyBatis Framework:MyBatis 的核心依賴。
- MySQL Driver:連接 MySQL 數(shù)據(jù)庫。
- Lombok:簡化實體類的開發(fā),減少樣板代碼。
2. 配置 pom.xml
以下是需要在 pom.xml 中添加的 Maven 依賴:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>這些依賴包括 Spring Boot 核心、MyBatis 框架、MySQL 數(shù)據(jù)庫驅(qū)動和 Lombok。版本號可以根據(jù)項目需求進行調(diào)整。
3. 配置數(shù)據(jù)庫連接
在 src/main/resources 目錄下創(chuàng)建 application.yml 文件,用于配置項目的數(shù)據(jù)庫連接。
application.yml 示例
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity說明:
url:數(shù)據(jù)庫連接地址。username和password:數(shù)據(jù)庫的用戶名和密碼。mapper-locations:指定 MyBatis 的 XML 映射文件路徑。type-aliases-package:指定實體類所在的包,用于啟用簡化的類名映射。
4. 創(chuàng)建數(shù)據(jù)庫表
使用以下 SQL 語句創(chuàng)建一個簡單的用戶表:
SQL 示例
CREATE DATABASE IF NOT EXISTS mybatis_demo;
USE mybatis_demo;
CREATE TABLE user (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);此 SQL 創(chuàng)建了一個名為 user 的表,用于存儲用戶信息。字段包括用戶 ID、用戶名、密碼、電子郵件以及創(chuàng)建時間。
5. 編寫實體類
創(chuàng)建與數(shù)據(jù)庫表對應(yīng)的 Java 實體類。
User.java
package com.example.demo.entity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id;
private String username;
private String password;
private String email;
private LocalDateTime createdAt;
}說明:
- 使用了 Lombok 的
@Data注解,自動生成getter、setter、toString等方法。 - 字段名稱與數(shù)據(jù)庫表的列名保持一致,便于自動映射。
6. 創(chuàng)建 Mapper 接口
MyBatis 的 Mapper 接口用于定義數(shù)據(jù)庫操作??梢赃x擇使用注解方式或者 XML 配置方式編寫 SQL。
注解方式 Mapper
以下是一個基于注解的 Mapper 接口示例:
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Insert("INSERT INTO user (username, password, email) VALUES (#{username}, #{password}, #{email})")
int insertUser(User user);
@Select("SELECT * FROM user WHERE id = #{id}")
User selectById(Long id);
@Select("SELECT * FROM user")
List<User> selectAllUsers();
@Update("UPDATE user SET username = #{username}, password = #{password}, email = #{email} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(Long id);
}XML 配置方式 Mapper
XML 配置方式更靈活,適合復(fù)雜查詢場景。以下是對應(yīng)的 XML 映射文件。
文件位置:src/main/resources/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.example.demo.mapper.UserMapper">
<insert id="insertUser" parameterType="com.example.demo.entity.User">
INSERT INTO user (username, password, email)
VALUES (#{username}, #{password}, #{email})
</insert>
<select id="selectById" parameterType="long" resultType="com.example.demo.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="selectAllUsers" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
<update id="updateUser" parameterType="com.example.demo.entity.User">
UPDATE user SET username = #{username}, password = #{password}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>在 Spring Boot 中,MyBatis 會自動掃描 mapper 文件夾下的 XML 文件。
7. 創(chuàng)建 Service 層
為了更好地分離業(yè)務(wù)邏輯,建議將 Mapper 操作封裝到 Service 層中。
UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public int createUser(User user) {
return userMapper.insertUser(user);
}
public User getUserById(Long id) {
return userMapper.selectById(id);
}
public List<User> getAllUsers() {
return userMapper.selectAllUsers();
}
public int updateUser(User user) {
return userMapper.updateUser(user);
}
public int deleteUser(Long id) {
return userMapper.deleteUser(id);
}
}8. 創(chuàng)建 Controller 層
最后,為了提供對外接口,創(chuàng)建 Controller。
UserController.java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping
public String createUser(@RequestBody User user) {
userService.createUser(user);
return "User created successfully!";
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PutMapping
public String updateUser(@RequestBody User user) {
userService.updateUser(user);
return "User updated successfully!";
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "User deleted successfully!";
}
}9. 啟動應(yīng)用
創(chuàng)建項目主類 MyBatisDemoApplication.java:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyBatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisDemoApplication.class, args);
}
}啟動項目,使用工具(如 Postman 或 CURL)測試接口。
四、MyBatis 基礎(chǔ)操作詳解
以下將詳細講解 MyBatis 的基礎(chǔ)操作,包括如何創(chuàng)建實體類、Mapper 接口、XML 映射文件,以及如何通過 Service 和 Controller 層完成基礎(chǔ)的增刪改查功能。
1. 創(chuàng)建實體類
實體類用于表示數(shù)據(jù)庫中的表記錄,在 MyBatis 中,實體類字段與數(shù)據(jù)庫表的列進行一一對應(yīng)。
示例代碼:User.java
package com.example.demo.entity;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id; // 用戶ID
private String username; // 用戶名
private String password; // 密碼
private String email; // 郵箱
private LocalDateTime createdAt; // 創(chuàng)建時間
}說明:
- 使用
@Data注解自動生成getter、setter、toString等方法。 - 字段名稱與數(shù)據(jù)庫表的列名保持一致,便于 MyBatis 自動映射。
2. 創(chuàng)建 Mapper 接口
Mapper 接口定義了對數(shù)據(jù)庫表的操作。MyBatis 支持兩種方式:基于注解和基于 XML 映射文件。
基于注解的 Mapper 接口
以下是使用注解定義的基礎(chǔ)增刪改查操作:
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
// 插入用戶
@Insert("INSERT INTO user (username, password, email) VALUES (#{username}, #{password}, #{email})")
int insertUser(User user);
// 查詢所有用戶
@Select("SELECT * FROM user")
List<User> getAllUsers();
// 根據(jù) ID 查詢用戶
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(Long id);
// 更新用戶
@Update("UPDATE user SET username = #{username}, password = #{password}, email = #{email} WHERE id = #{id}")
int updateUser(User user);
// 刪除用戶
@Delete("DELETE FROM user WHERE id = #{id}")
int deleteUser(Long id);
}注意:
- 使用
@Mapper注解讓 Spring 容器自動掃描 Mapper 接口。 - 注解方式適合簡單的 SQL 語句,對于復(fù)雜查詢建議使用 XML。
3. 配置 XML 映射文件
在復(fù)雜查詢場景中,XML 配置文件更加靈活。
文件位置
src/main/resources/mapper/UserMapper.xml
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.example.demo.mapper.UserMapper">
<!-- 定義字段與屬性的映射 -->
<resultMap id="UserResultMap" type="com.example.demo.entity.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
<result column="email" property="email" />
<result column="created_at" property="createdAt" />
</resultMap>
<!-- 查詢所有用戶 -->
<select id="getAllUsers" resultMap="UserResultMap">
SELECT * FROM user
</select>
<!-- 插入用戶 -->
<insert id="insertUser" parameterType="com.example.demo.entity.User">
INSERT INTO user (username, password, email)
VALUES (#{username}, #{password}, #{email})
</insert>
<!-- 更新用戶 -->
<update id="updateUser" parameterType="com.example.demo.entity.User">
UPDATE user
SET username = #{username}, password = #{password}, email = #{email}
WHERE id = #{id}
</update>
<!-- 刪除用戶 -->
<delete id="deleteUser" parameterType="long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>注意:
namespace必須與 Mapper 接口的全路徑名稱一致。<resultMap>定義了表字段與實體類屬性之間的映射關(guān)系。#{}用于參數(shù)占位,MyBatis 會根據(jù)參數(shù)類型自動替換。
4. 創(chuàng)建 Service 層
為了實現(xiàn)業(yè)務(wù)邏輯與數(shù)據(jù)訪問的分離,建議通過 Service 層封裝 Mapper 的操作。
示例代碼:UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
// 添加用戶
public int addUser(User user) {
return userMapper.insertUser(user);
}
// 獲取所有用戶
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
// 根據(jù) ID 查詢用戶
public User getUserById(Long id) {
return userMapper.getUserById(id);
}
// 更新用戶
public int updateUser(User user) {
return userMapper.updateUser(user);
}
// 刪除用戶
public int deleteUser(Long id) {
return userMapper.deleteUser(id);
}
}說明:
- 通過依賴注入的方式引入
UserMapper。 - 將所有的數(shù)據(jù)庫操作封裝為獨立的方法,便于管理和復(fù)用。
5. 創(chuàng)建 Controller 層
Controller 層提供 RESTful API 接口,供外部訪問 Service 方法。 示例代碼:UserController.java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// 創(chuàng)建用戶
@PostMapping
public String createUser(@RequestBody User user) {
userService.addUser(user);
return "User created successfully!";
}
// 獲取所有用戶
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
// 根據(jù) ID 獲取用戶
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
// 更新用戶
@PutMapping
public String updateUser(@RequestBody User user) {
userService.updateUser(user);
return "User updated successfully!";
}
// 刪除用戶
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "User deleted successfully!";
}
}說明:
- 使用
@RestController標(biāo)注類,返回 JSON 數(shù)據(jù)。 - 通過
@RequestBody接收前端傳遞的 JSON 數(shù)據(jù)。 - 通過
@PathVariable獲取 URL 中的動態(tài)參數(shù)。
五、高級功能
1. 動態(tài) SQL
動態(tài) SQL 是 MyBatis 的強大功能之一,可以根據(jù)輸入條件動態(tài)生成 SQL 語句。相比手動拼接 SQL,這種方式更加安全、高效且可維護。
1.1 動態(tài) SQL 標(biāo)簽
MyBatis 提供了以下動態(tài) SQL 標(biāo)簽:
<if>:用于條件判斷。<choose>:類似于 Java 的switch-case。<where>:自動添加WHERE關(guān)鍵字并處理多個條件。<set>:動態(tài)生成SET子句,常用于更新語句。<foreach>:用于迭代生成 SQL(如IN子句或批量插入)。<trim>:自定義 SQL 前后綴(如添加括號、處理多余逗號等)。
1.2 動態(tài) SQL 示例
(1)條件查詢:根據(jù)用戶輸入動態(tài)生成查詢條件
XML 配置文件:
<select id="searchUsers" resultMap="UserResultMap">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>注意:
<where>標(biāo)簽會自動處理條件的拼接,并在至少有一個條件成立時自動添加WHERE關(guān)鍵字。
Java 調(diào)用代碼:
Map<String, Object> params = new HashMap<>();
params.put("username", "John");
params.put("email", null);
List<User> users = userMapper.searchUsers(params);(2)動態(tài)更新:根據(jù)非空字段更新用戶信息
在實際場景中,往往需要對部分字段進行更新,MyBatis 的動態(tài) SQL 可以輕松實現(xiàn)。
XML 配置文件:
<update id="updateUser" parameterType="User">
UPDATE user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="email != null">
email = #{email},
</if>
</set>
WHERE id = #{id}
</update>注意:
<set>標(biāo)簽會自動處理逗號,確保生成的 SQL 語句語法正確。null值的字段會被忽略,避免誤更新。
Java 調(diào)用代碼:
User user = new User();
user.setId(1L);
user.setUsername("NewName");
int rows = userMapper.updateUser(user);(3)批量查詢:使用 <foreach> 生成 IN 子句
XML 配置文件:
<select id="findUsersByIds" resultMap="UserResultMap">
SELECT * FROM user
WHERE id IN
<foreach collection="idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>說明:
collection指定輸入?yún)?shù)(一般為 List 或數(shù)組)。item是每次迭代的變量。open、separator和close分別定義 SQL 子句的開頭、分隔符和結(jié)尾。
Java 調(diào)用代碼:
List<Long> idList = Arrays.asList(1L, 2L, 3L); List<User> users = userMapper.findUsersByIds(idList);
生成的 SQL:
SELECT * FROM user WHERE id IN (1, 2, 3);
2. 分頁查詢
分頁查詢是 Web 應(yīng)用中最常見的功能之一。在 MyBatis 中,可以借助 PageHelper 插件實現(xiàn)高效分頁。
2.1 使用 PageHelper 插件
(1)引入依賴
在 pom.xml 中添加以下依賴:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.0</version>
</dependency>(2)分頁查詢示例
在 Service 層調(diào)用分頁方法:
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
public List<User> getUsersByPage(int pageNum, int pageSize) {
// 啟用分頁
PageHelper.startPage(pageNum, pageSize);
List<User> users = userMapper.getAllUsers();
// 封裝分頁結(jié)果
return new PageInfo<>(users).getList();
}(3)自定義分頁
如果不想引入插件,也可以通過手動拼接分頁 SQL:
XML 配置文件:
<select id="getUsersByPage" resultMap="UserResultMap">
SELECT * FROM user
LIMIT #{offset}, #{pageSize}
</select>Mapper 接口:
List<User> getUsersByPage(@Param("offset") int offset, @Param("pageSize") int pageSize);Java 調(diào)用代碼:
int offset = (pageNum - 1) * pageSize; List<User> users = userMapper.getUsersByPage(offset, pageSize);
3. 復(fù)雜對象映射
3.1 一對多映射
場景:一個用戶有多個訂單。
數(shù)據(jù)庫表設(shè)計:
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
user_id BIGINT,
order_name VARCHAR(255),
FOREIGN KEY (user_id) REFERENCES user(id)
);XML 配置文件:
<resultMap id="UserWithOrders" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<collection property="orders" ofType="Order">
<id column="order_id" property="id"/>
<result column="order_name" property="orderName"/>
</collection>
</resultMap>
<select id="getUserWithOrders" resultMap="UserWithOrders">
SELECT u.id, u.username, o.id AS order_id, o.order_name
FROM user u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.id = #{id}
</select>3.2 嵌套查詢
對于復(fù)雜的多表查詢,可以使用嵌套查詢實現(xiàn)。
XML 配置:
<resultMap id="OrderResultMap" type="Order">
<id column="id" property="id"/>
<result column="order_name" property="orderName"/>
</resultMap>
<resultMap id="UserWithOrders" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<collection property="orders" resultMap="OrderResultMap" column="id"/>
</resultMap>
<select id="getUserWithOrders" resultMap="UserWithOrders">
SELECT * FROM user WHERE id = #{id};
</select>六、最佳實踐
1. 分層設(shè)計
- Controller 層:負(fù)責(zé)接收請求和返回響應(yīng)。
- Service 層:封裝業(yè)務(wù)邏輯。
- Mapper 層:專注于數(shù)據(jù)庫交互。
2. 避免 N+1 查詢
一對多、多對多場景中,優(yōu)先使用聯(lián)合查詢或嵌套查詢,避免多個 SQL 執(zhí)行。
3. 啟用日志
在 application.yml 中啟用 MyBatis 日志:
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl4. 動態(tài) SQL 使用
<foreach>實現(xiàn)批量操作。- 使用
<if>結(jié)合<set>實現(xiàn)動態(tài)更新。
總結(jié)
MyBatis 的高級功能如動態(tài) SQL、分頁查詢和復(fù)雜對象映射,為開發(fā)者提供了極大的靈活性。在項目中,結(jié)合實際場景選擇合適的實現(xiàn)方式,可以顯著提高開發(fā)效率并降低維護成本。如果有任何疑問,歡迎在評論區(qū)留言討論!
到此這篇關(guān)于Spring Boot 集成 MyBatis 全面講解(最新推薦)的文章就介紹到這了,更多相關(guān)Spring Boot 集成 MyBatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 5分鐘快速搭建SpringBoot3?+?MyBatis-Plus工程/項目的實現(xiàn)示例
- 解決mybatis-plus-boot-starter與mybatis-spring-boot-starter的錯誤問題
- Spring Boot 中整合 MyBatis-Plus詳細步驟(最新推薦)
- Spring Boot 中使用 Mybatis Plus的操作方法
- SpringBoot同時集成Mybatis和Mybatis-plus框架
- Springboot使用MybatisPlus實現(xiàn)mysql樂觀鎖
- 淺談Spring Boot、MyBatis、MyBatis-Plus 依賴版本對應(yīng)關(guān)系
- Spring Boot Mybatis++ 2025詳解
相關(guān)文章
Spring Security @PreAuthorize注解分析
本教程介紹了如何使用 Spring 方法級安全和 @PreAuthorize 注解來保護 RestController 方法,通過這些步驟,您可以確保只有具有適當(dāng)角色或權(quán)限的用戶才能訪問特定的 REST API,感興趣的朋友跟隨小編一起看看吧2024-11-11
Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時遇到的結(jié)點為空的問題詳解
這篇文章主要介紹了Java版數(shù)據(jù)結(jié)構(gòu)插入數(shù)據(jù)時遇到的結(jié)點為空的問題及解決辦法,需要的朋友們可以學(xué)習(xí)下。2019-09-09
java統(tǒng)計文件中每個字符出現(xiàn)的個數(shù)
這篇文章主要為大家詳細介紹了java統(tǒng)計文件中每個字符出現(xiàn)的個數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-03-03

