SpringBoot集成tk.mybatis實(shí)踐
一 Spring Boot 集成 tk.mybatis
tk.mybatis 是 MyBatis 的一個(gè)插件,用于簡化 MyBatis 的開發(fā)。
1.添加依賴
Spring Boot 項(xiàng)目中的 pom.xml 文件中添加 MyBatis、TkMyBatis 和 MySQL的依賴。
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version> <!-- 請根據(jù)實(shí)際情況選擇版本 -->
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version> <!-- 請根據(jù)實(shí)際情況選擇版本 -->
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version> <!-- 請根據(jù)實(shí)際情況選擇版本 -->
</dependency>2.配置數(shù)據(jù)源
在 application.properties 或 application.yml 文件中配置數(shù)據(jù)源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mydatabase
username: your_username
password: your_password或者
spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.創(chuàng)建實(shí)體類
創(chuàng)建對應(yīng)數(shù)據(jù)庫表的實(shí)體類,并確保屬性與表字段一一對應(yīng)。
@Table 注解指定對應(yīng)的數(shù)據(jù)庫表
import javax.persistence.*;
import lombok.Data;
@Data
@Table(name = "your_table")
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private String name;
}
4.創(chuàng)建Mapper接口
創(chuàng)建Mapper接口繼承自 Mapper<T>,其中 T 是實(shí)體類的類型。
import tk.mybatis.mapper.common.Mapper;
public interface YourMapper extends Mapper<YourEntity> {
// 這里可以添加自定義的查詢方法
}
5.啟動(dòng)類上添加注解
在 Spring Boot 的啟動(dòng)類上添加 @MapperScan 注解,指定 Mapper接口的包路徑。
@MapperScan:tk.mybatis.spring.annotation.MapperScan
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan(basePackages = "com.example.yourapp.mapper")
@SpringBootApplication
public class SpringbootMainApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMainApplication.class, args);
}
}
6.使用Mapper
在 Service 類中注入 Mapper并使用它。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class YourService {
@Autowired
private YourMapper yourMapper;
public List<YourEntity> getAllEntities() {
return yourMapper.selectAll();
}
// Add other methods as needed
}
二 對象和數(shù)據(jù)庫記錄映射
如果實(shí)體類的實(shí)例字段中包含對象,需要考慮如何對象和數(shù)據(jù)庫記錄如何相互映射。
通常情況下,使用 MyBatis 的 TypeHandler來處理對象字段的映射。
1.實(shí)體類(包含對象字段)
@ColumnType 注解作用:指定 OtherObjectTypeHandler.class 作為類型處理器
import lombok.Data;
import tk.mybatis.mapper.annotation.ColumnType;
import javax.persistence.*;
@Data
@Table(name = "your_table")
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
private String name;
// 對象字段
@Column(name = "other_object")
@ColumnType(typeHandler = OtherObjectTypeHandler.class)
private OtherObject otherObject;
}
2.映射(TypeHandler)
繼承BaseTypeHandler抽象類,創(chuàng)建一個(gè) TypeHandler類來處理 Object對象字段的映射(對象與數(shù)據(jù)庫字段的轉(zhuǎn)換)。
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OtherObjectTypeHandler extends BaseTypeHandler<OtherObject> {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, OtherObject parameter, JdbcType jdbcType) throws SQLException {
// 設(shè)置 PreparedStatement 中的參數(shù),將 OtherObject 對象轉(zhuǎn)換為需要的類型
try {
ps.setObject(i, objectMapper.writeValueAsString(parameter));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public OtherObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
// 從 ResultSet 中獲取數(shù)據(jù)并轉(zhuǎn)換為 OtherObject 對象
try {
return objectMapper.readValue(rs.getString(columnName), OtherObject.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public OtherObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
// 從 ResultSet 中獲取數(shù)據(jù)并轉(zhuǎn)換為 OtherObject 對象
try {
return objectMapper.readValue(rs.getString(columnIndex), OtherObject.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public OtherObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
// 從 CallableStatement 中獲取數(shù)據(jù)并轉(zhuǎn)換為 OtherObject 對象
try {
return objectMapper.readValue(cs.getString(columnIndex), OtherObject.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
三 Example的應(yīng)用
在 tk.mybatis 中,Example 類提供了一種便捷的方式來構(gòu)建動(dòng)態(tài)的 SQL 查詢條件。
通過使用 Example 類,可以在不同的場景下動(dòng)態(tài)地構(gòu)建查詢條件,而不需要手動(dòng)編寫復(fù)雜的 SQL 語句。
import org.lbb.mapper.YourMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;
@Service
public class YourService {
@Autowired
private YourMapper yourMapper;
/**
* 根據(jù) id 獲取實(shí)體
*/
public YourEntity getEntity(String id) {
// 1.創(chuàng)建 Example 對象
Example example = new Example(YourEntity.class);
// 2.創(chuàng)建 Criteria 對象,用于設(shè)置查詢條件
Example.Criteria criteria = example.createCriteria();
// 3.設(shè)置查詢條件
criteria.andEqualTo("id", id);
return yourMapper.selectOneByExample(example);
}
/**
* 根據(jù) name 獲取實(shí)體
*/
public List<YourEntity> getEnties(String name) {
// 1.創(chuàng)建 Example 對象
Example example = new Example(YourEntity.class);
// 2.創(chuàng)建 Criteria 對象,用于設(shè)置查詢條件
Example.Criteria criteria = example.createCriteria();
// 3.設(shè)置查詢條件
criteria.andEqualTo("name", name);
return yourMapper.selectByExample(example);
}
}
Criteria 對象中可以添加不同的條件,比如 andEqualTo、andLike、andGreaterThan 等等,來實(shí)現(xiàn)更加靈活的查詢。
四 分頁
1.PageHelper
分頁攔截器
依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>{pagehelper-version}</version>
</dependency>public List<YourEntity> pagingByPageHelper(int pageNum, int pageSize) {
// 設(shè)置分頁參數(shù)
PageHelper.startPage(pageNum, pageSize);
// 執(zhí)行查詢
List<YourEntity> entities = yourMapper.selectAll();
// 獲取分頁信息
PageInfo<YourEntity> pageInfo = new PageInfo<>(entities);
log.info("{}", pageInfo.getPageNum());
// 返回分頁結(jié)果
return pageInfo.getList();
}
pageNum 和 pageSize,分別表示要查詢的頁碼和每頁顯示的記錄數(shù)。
通過 PageHelper.startPage 方法設(shè)置分頁參數(shù)。
查詢結(jié)果會(huì)被自動(dòng)分頁,存儲在 PageInfo 對象中,可以從中獲取分頁信息和當(dāng)前頁的數(shù)據(jù)列表。
2.RowBounds
RowBounds 是 MyBatis 提供的一種簡單的分頁實(shí)現(xiàn)方式,它通過在查詢時(shí)指定起始行和返回的最大行數(shù)來實(shí)現(xiàn)分頁。
在 tk.mybatis 中,selectByRowBounds 方法可以直接在 Mapper 接口中使用,它接受兩個(gè)參數(shù):
- 查詢條件(實(shí)體屬性)
- RowBounds 對象
public List<YourEntity> pagingByRowBounds(int pageNum, int pageSize) {
// 創(chuàng)建 PageRowBounds 對象,表示分頁的起始行和每頁顯示的行數(shù)
PageRowBounds pageRowBounds = new PageRowBounds((pageNum - 1) * pageSize, pageSize);
// 執(zhí)行分頁查詢,傳入查詢條件(實(shí)體屬性)和 PageRowBounds 對象
List<YourEntity> entities = yourMapper.selectByRowBounds(null, pageRowBounds);
return entities;
}
創(chuàng)建 PageRowBounds 對象,設(shè)置起始行和每頁顯示的行數(shù)。
調(diào)用 yourMapper.selectByRowBounds 方法執(zhí)行分頁查詢,傳入了查詢條件為 null(表示查詢所有記錄)和 PageRowBounds 對象。
在使用 selectByRowBounds 方法時(shí),需要手動(dòng)計(jì)算分頁的起始行,并創(chuàng)建對應(yīng)的 PageRowBounds 對象。
這種方式相對比較底層,需要更多的手動(dòng)操作,但在某些情況下可能更加靈活。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Java基于SpringBoot和tk.mybatis實(shí)現(xiàn)事務(wù)讀寫分離代碼實(shí)例
- SpringBoot2.0整合tk.mybatis異常解決
- SpringBoot3.x與MyBatis-Plus兼容問題小結(jié)
- SpringBoot+MyBatis處理JSON字段的完整指南
- mybatis-plus集成springboot實(shí)現(xiàn)XML映射器方式
- SpringBoot+Mybatis通過自定義注解實(shí)現(xiàn)字段加密存儲方式
- SpringBoot+MyBatis實(shí)現(xiàn)數(shù)據(jù)庫字段加密全過程
- SpringBoot整合Junit與Mybatis實(shí)戰(zhàn)指南
相關(guān)文章
關(guān)于mybatis-plus-generator的簡單使用示例詳解
在springboot項(xiàng)目中集成mybatis-plus是很方便開發(fā)的,最近看了一下plus的文檔,簡單用一下它的代碼生成器,接下來通過實(shí)例代碼講解關(guān)于mybatis-plus-generator的簡單使用,感興趣的朋友跟隨小編一起看看吧2024-03-03
MyBatis中的循環(huán)插入insert foreach問題
這篇文章主要介紹了MyBatis中的循環(huán)插入insert foreach問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
Java兩種動(dòng)態(tài)代理JDK動(dòng)態(tài)代理和CGLIB動(dòng)態(tài)代理詳解
這篇文章主要介紹了Java兩種動(dòng)態(tài)代理JDK動(dòng)態(tài)代理和CGLIB動(dòng)態(tài)代理詳解,代理模式是23種設(shè)計(jì)模式的一種,他是指一個(gè)對象A通過持有另一個(gè)對象B,可以具有B同樣的行為的模式,為了對外開放協(xié)議,B往往實(shí)現(xiàn)了一個(gè)接口,A也會(huì)去實(shí)現(xiàn)接口,需要的朋友可以參考下2023-11-11
SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例
這篇文章主要介紹了SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例,文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-06-06
Java實(shí)現(xiàn)深度優(yōu)先搜索(DFS)和廣度優(yōu)先搜索(BFS)算法
深度優(yōu)先搜索(DFS)和廣度優(yōu)先搜索(BFS)是兩種基本的圖搜索算法,可用于圖的遍歷、路徑搜索等問題。DFS采用棧結(jié)構(gòu)實(shí)現(xiàn),從起點(diǎn)開始往深處遍歷,直到找到目標(biāo)節(jié)點(diǎn)或遍歷完整個(gè)圖;BFS采用隊(duì)列結(jié)構(gòu)實(shí)現(xiàn),從起點(diǎn)開始往廣處遍歷,直到找到目標(biāo)節(jié)點(diǎn)或遍歷完整個(gè)圖2023-04-04
解析Spring框架中的XmlBeanDefinitionStoreException異常情況
這篇文章主要介紹了解析Spring框架中的XmlBeanDefinitionStoreException異常情況,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
java底層AQS實(shí)現(xiàn)類ReentrantLock鎖的構(gòu)成及源碼解析
本章我們就要來學(xué)習(xí)一下第一個(gè)?AQS?的實(shí)現(xiàn)類:ReentrantLock,看看其底層是如何組合?AQS?,實(shí)現(xiàn)了自己的那些功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
SpringBoot生產(chǎn)環(huán)境打包如何去除無用依賴
這篇文章主要介紹了SpringBoot生產(chǎn)環(huán)境打包如何去除無用依賴問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09

