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

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

