Spring Boot 集成 MyBatis 全攻略(最新整理)
Spring Boot 集成 MyBatis 全攻略
1. 為什么選擇 MyBatis
- ORM 靈活性:相比 Hibernate,MyBatis 更靈活,SQL 可控,性能優(yōu)化空間大。
- 學習曲線低:對于熟悉 SQL 的開發(fā)者,上手快。
- 與 Spring Boot 無縫整合:只需少量配置,即可快速使用。
2. 基礎(chǔ)環(huán)境
依賴(pom.xml)
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis-Spring-Boot-Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 數(shù)據(jù)庫驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok(可選) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>3. 配置數(shù)據(jù)源
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root123
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
# 指定 Mapper XML 文件位置
mapper-locations: classpath:mapper/*.xml
# 指定實體類包,自動映射列名和屬性名(開啟駝峰命名)
type-aliases-package: com.example.demo.entity
configuration:
map-underscore-to-camel-case: true4. 定義實體類
package com.example.demo.entity;
import lombok.Data;
@Data
public class User {
private Long id;
private String username;
private String email;
}5. 定義 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 {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Select("SELECT * FROM user")
List<User> findAll();
@Insert("INSERT INTO user(username, email) VALUES(#{username}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
@Update("UPDATE user SET username=#{username}, email=#{email} WHERE id=#{id}")
int update(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
int delete(Long id);
}? 這里用注解方式,簡單清晰;復(fù)雜 SQL 可以寫到 XML 文件。
6. 使用 XML 配置 SQL(適合復(fù)雜 SQL)
在 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">
<select id="findAll" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
<insert id="insert" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(username, email) VALUES(#{username}, #{email})
</insert>
</mapper>7. Service + Controller
Service
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 User getUser(Long id) {
return userMapper.findById(id);
}
public List<User> listUsers() {
return userMapper.findAll();
}
public int addUser(User user) {
return userMapper.insert(user);
}
}Controller
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("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping
public List<User> listUsers() {
return userService.listUsers();
}
@PostMapping
public String addUser(@RequestBody User user) {
userService.addUser(user);
return "User added successfully!";
}
}8. 分頁支持
推薦集成 PageHelper 插件:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.7</version>
</dependency>使用:
PageHelper.startPage(1, 10); List<User> users = userMapper.findAll(); PageInfo<User> pageInfo = new PageInfo<>(users);
9. 常見優(yōu)化
- 批量插入:使用
foreach標簽。 - 動態(tài) SQL:使用
<if><choose>等標簽構(gòu)建靈活查詢。 - 二級緩存:
<cache/>配置 + Redis 集成。 - 多數(shù)據(jù)源:Spring Boot + MyBatis 支持動態(tài)數(shù)據(jù)源切換。
- 統(tǒng)一異常處理:結(jié)合
@ControllerAdvice統(tǒng)一返回接口錯誤信息。
10. 總結(jié)
Spring Boot + MyBatis 集成流程大致分為:
- 加依賴 → 2. 配數(shù)據(jù)源 → 3. 寫實體類 → 4. 寫 Mapper(注解/XML) → 5. 寫 Service/Controller → 6. 增強功能(分頁、緩存、動態(tài) SQL)。
這樣,就能快速搭建一個 基于 Spring Boot + MyBatis 的全棧開發(fā)框架 ??。
到此這篇關(guān)于Spring Boot 集成 MyBatis 全攻略(最新整理)的文章就介紹到這了,更多相關(guān)Spring Boot 集成 MyBatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot同時集成Mybatis和Mybatis-plus框架
- Spring Boot集成MyBatis-Plus 自定義攔截器實現(xiàn)動態(tài)表名切換功能
- SpringBoot與MyBatis-Plus的高效集成方式
- springboot集成mybatis-plus全過程
- Springboot集成Mybatis-plus、ClickHouse實現(xiàn)增加數(shù)據(jù)、查詢數(shù)據(jù)功能
- SpringBoot3.0集成MybatisPlus的實現(xiàn)方法
- MyBatis-Plus介紹及Spring Boot 3集成指南
- SpringBoot集成MyBatis的多種方式
- SpringBoot中MyBatis-Flex的集成和使用實現(xiàn)
相關(guān)文章
Java數(shù)據(jù)庫存儲數(shù)組的方法小結(jié)
在現(xiàn)代軟件開發(fā)中,數(shù)組是常用的數(shù)據(jù)結(jié)構(gòu)之一,然而,在關(guān)系數(shù)據(jù)庫中直接存儲數(shù)組并不是一個簡單的任務(wù),本文將詳細介紹幾種在Java中將數(shù)組存儲到數(shù)據(jù)庫的方法,包括使用JPA、JSON、XML、以及關(guān)系型數(shù)據(jù)庫的數(shù)組類型等,需要的朋友可以參考下2024-09-09
詳解SpringBoot結(jié)合swagger2快速生成簡單的接口文檔
這篇文章主要介紹了詳解SpringBoot結(jié)合swagger2快速生成簡單的接口文檔,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
Java concurrency之LockSupport_動力節(jié)點Java學院整理
這篇文章主要為大家詳細介紹了Java concurrency之LockSupport的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
SpringBoot中TransactionTemplate事務(wù)管理的實現(xiàn)
Spring Boot提供了多種方式來管理事務(wù),其中之一是使用TransactionTemplate,本文主要介紹了SpringBoot中TransactionTemplate事務(wù)管理的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-04-04
Java實現(xiàn)視頻格式轉(zhuǎn)換的完整指南
在Java中實現(xiàn)視頻格式的轉(zhuǎn)換,通常需要借助第三方工具或庫,因為視頻的編解碼操作復(fù)雜且性能需求較高,以下是實現(xiàn)視頻格式轉(zhuǎn)換的常用方法和步驟,需要的朋友可以參考下2025-05-05
細數(shù)Java接口的概念、分類及與抽象類的區(qū)別
下面小編就為大家?guī)硪黄殧?shù)Java接口的概念、分類及與抽象類的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
Mybatis操作多數(shù)據(jù)源的實現(xiàn)
本文主要介紹了Mybatis操作多數(shù)據(jù)源,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05

