Spring Boot與MyBatis配置與操作實(shí)戰(zhàn)指南
Spring Boot與MyBatis的配置
一、簡(jiǎn)介
Spring Boot是一個(gè)用于創(chuàng)建獨(dú)立的、基于Spring的生產(chǎn)級(jí)應(yīng)用程序的框架,它簡(jiǎn)化了Spring應(yīng)用的初始搭建以及開發(fā)過(guò)程。MyBatis是一款優(yōu)秀的持久層框架,它支持定制化SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。將Spring Boot和MyBatis結(jié)合使用,可以高效地開發(fā)數(shù)據(jù)驅(qū)動(dòng)的應(yīng)用程序。

二、環(huán)境準(zhǔn)備
(一)創(chuàng)建Spring Boot項(xiàng)目
- 可以使用Spring Initializr(https://start.spring.io/)來(lái)創(chuàng)建一個(gè)基礎(chǔ)的Spring Boot項(xiàng)目。
- 在創(chuàng)建項(xiàng)目時(shí),選擇合適的項(xiàng)目元數(shù)據(jù),如項(xiàng)目的Group和Artifact等信息。
- 可以選擇添加一些常用的依賴,如Web依賴(如果項(xiàng)目需要提供Web服務(wù))等。不過(guò),對(duì)于MyBatis的集成,初始創(chuàng)建時(shí)不需要專門添加MyBatis相關(guān)依賴,我們后續(xù)手動(dòng)添加。
- 下載生成的項(xiàng)目壓縮包并解壓到本地開發(fā)環(huán)境。
(二)添加MyBatis依賴
在項(xiàng)目的pom.xml(如果是Maven項(xiàng)目)中添加MyBatis和相關(guān)數(shù)據(jù)庫(kù)驅(qū)動(dòng)的依賴。
對(duì)于MyBatis本身: ?????
org.mybatis.spring.boot
mybatis - spring - boot - starter
2.2.2如果使用MySQL數(shù)據(jù)庫(kù),添加MySQL驅(qū)動(dòng)依賴: ??????
mysql
mysql - connector - java
8.0.26三、數(shù)據(jù)庫(kù)配置
(一)配置數(shù)據(jù)源
在Spring Boot的配置文件(application.properties或者application.yml)中配置數(shù)據(jù)源相關(guān)信息。
如果使用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配置
(一)實(shí)體類創(chuàng)建
根據(jù)數(shù)據(jù)庫(kù)表結(jié)構(gòu)創(chuàng)建對(duì)應(yīng)的實(shí)體類。例如,如果有一個(gè)名為“user”的表,結(jié)構(gòu)如下:
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50),
password VARCHAR(50)
);對(duì)應(yīng)的Java實(shí)體類為:
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接口創(chuàng)建
創(chuàng)建Mapper接口來(lái)定義與數(shù)據(jù)庫(kù)交互的方法。
例如,創(chuàng)建一個(gè)UserMapper接口:
@Mapper
public interface UserMapper {
User selectUserById(Integer id);
int insertUser(User user);
int updateUser(User user);
int deleteUserById(Integer id);
}這里的@Mapper注解(如果使用注解方式)用于將該接口標(biāo)記為MyBatis的Mapper接口,這樣Spring Boot就能夠識(shí)別并自動(dòng)創(chuàng)建該接口的代理實(shí)現(xiàn)。
(三)Mapper XML文件創(chuàng)建(如果使用XML方式)
如果不使用注解方式編寫SQL語(yǔ)句,而是使用XML文件,則需要?jiǎng)?chuàng)建Mapper XML文件。
在resources/mapper目錄下創(chuàng)建UserMapper.xml(假設(shè)項(xiàng)目采用的是Maven的標(biāo)準(zhǔn)目錄結(jié)構(gòu))。
內(nèi)容如下:
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屬性的值要與對(duì)應(yīng)的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進(jìn)行數(shù)據(jù)操作
(一)在Service層調(diào)用Mapper方法
創(chuàng)建一個(gè)UserService類來(lái)調(diào)用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);
}
}這里通過(guò)@Autowired注解注入U(xiǎn)serMapper實(shí)例,然后就可以在Service方法中調(diào)用Mapper中的數(shù)據(jù)操作方法。
(二)在Controller層調(diào)用Service方法(如果是Web應(yīng)用)
創(chuàng)建一個(gè)UserController類(假設(shè)是一個(gè)Web應(yīng)用,需要提供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);
}
}這里同樣通過(guò)@Autowired注解注入U(xiǎn)serService實(shí)例,然后在Controller的各個(gè)方法中調(diào)用Service方法,實(shí)現(xiàn)了從Web請(qǐng)求到數(shù)據(jù)操作的完整流程。
六、事務(wù)管理
在Spring Boot中管理MyBatis的事務(wù)非常方便。
如果要在某個(gè)Service方法上添加事務(wù)管理,可以使用@Transactional注解。例如:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
@Transactional
public int addUser(User user) {
// 一些業(yè)務(wù)邏輯判斷等操作
int result = userMapper.insertUser(user);
// 如果插入成功后還有其他操作,如更新相關(guān)聯(lián)的數(shù)據(jù)等
return result;
}
}這樣,如果在addUser方法中的任何一個(gè)數(shù)據(jù)庫(kù)操作出現(xiàn)異常,整個(gè)事務(wù)都會(huì)回滾,保證數(shù)據(jù)的一致性。
七、高級(jí)配置
(一)配置MyBatis的緩存
- MyBatis提供了一級(jí)緩存和二級(jí)緩存。
- 一級(jí)緩存是基于SqlSession的,默認(rèn)是開啟的。
- 二級(jí)緩存可以通過(guò)在Mapper接口或者M(jìn)apper XML文件中配置開啟。
- 在Mapper XML文件中配置二級(jí)緩存:
- 這里的標(biāo)簽用于配置二級(jí)緩存的相關(guān)屬性,如緩存的清除策略(eviction)、刷新間隔(flushInterval)、緩存大?。╯ize)和是否只讀(readOnly)等。
(二)配置MyBatis的插件
MyBatis允許使用插件來(lái)擴(kuò)展其功能。例如,可以使用PageHelper插件來(lái)實(shí)現(xiàn)分頁(yè)功能。
首先添加PageHelper的依賴:
com.github.pagehelper
pagehelper - spring - boot - starter
1.3.0然后在配置文件中進(jìn)行簡(jiǎn)單配置(以application.yml為例):
pagehelper: helper - dialect: mysql reasonable: true support - methods - arguments: true
在使用分頁(yè)查詢時(shí),在Mapper接口方法調(diào)用之前使用PageHelper.startPage方法即可。例如:
public class UserService {
@Autowired
private UserMapper userMapper;
public List getUsersByPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectAllUsers();
}
}通過(guò)以上的配置和操作步驟,就可以在Spring Boot項(xiàng)目中成功地集成和使用MyBatis進(jìn)行高效的數(shù)據(jù)持久化操作,無(wú)論是簡(jiǎn)單的CRUD操作還是涉及到高級(jí)功能如事務(wù)管理、緩存和插件的使用等。
到此這篇關(guān)于Spring Boot與MyBatis配置與操作實(shí)戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Spring Boot與MyBatis配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中的ConcurrentLinkedQueue使用解析
這篇文章主要介紹了Java中的ConcurrentLinkedQueue使用解析,一個(gè)基于鏈接節(jié)點(diǎn)的無(wú)界線程安全隊(duì)列,此隊(duì)列按照 FIFO(先進(jìn)先出)原則對(duì)元素進(jìn)行排序,隊(duì)列的頭部是隊(duì)列中時(shí)間最長(zhǎng)的元素,需要的朋友可以參考下2023-12-12
Springboot如何優(yōu)雅地進(jìn)行字段校驗(yàn)
這篇文章主要給大家介紹了關(guān)于Springboot如何優(yōu)雅地進(jìn)行字段校驗(yàn)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Slf4j+logback實(shí)現(xiàn)JSON格式日志輸出方式
這篇文章主要介紹了Slf4j+logback實(shí)現(xiàn)JSON格式日志輸出方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
工作中禁止使用Executors快捷創(chuàng)建線程池原理詳解
這篇文章主要為大家介紹了工作中禁止使用Executors快捷創(chuàng)建線程池原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Java實(shí)現(xiàn)簡(jiǎn)單字符生成器代碼例子
這篇文章主要介紹了Java實(shí)現(xiàn)簡(jiǎn)單字符生成器代碼例子,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-06-06
超級(jí)詳細(xì)Java?JDK環(huán)境配置教程(Mac?版)
這篇文章詳細(xì)講解了在MacOS上安裝JDK及配置Java環(huán)境的步驟,包括下載JDK安裝包、安裝JDK、查詢安裝路徑以及配置環(huán)境變量,旨在為初學(xué)者提供一份保姆級(jí)的安裝指南,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10

