Spring Boot 集成 tk.mybatis

2024-04-23 09:04
文章标签 java spring boot 集成 mybatis tk

本文主要是介绍Spring Boot 集成 tk.mybatis,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一 Spring Boot 集成 tk.mybatis

tk.mybatis 是 MyBatis 的一个插件,用于简化 MyBatis 的开发。

1.添加依赖

Spring Boot 项目中的 pom.xml 文件中添加 MyBatis、TkMyBatis 和 MySQL的依赖。

<dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.1.5</version> <!-- 请根据实际情况选择版本 -->
</dependency>
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version> <!-- 请根据实际情况选择版本 -->
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version> <!-- 请根据实际情况选择版本 -->
</dependency>

2.配置数据源

application.propertiesapplication.yml 文件中配置数据源

spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mydatabaseusername: your_usernamepassword: 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.创建实体类

创建对应数据库表实体类,并确保属性与表字段一一对应

@Table 注解指定对应的数据库表

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.创建 Mapper接口

创建Mapper接口继承自 Mapper<T>,其中 T 是实体类的类型。

import tk.mybatis.mapper.common.Mapper;public interface YourMapper extends Mapper<YourEntity> {// 这里可以添加自定义的查询方法
}

5.启动类上添加注解

Spring Boot 的启动类上添加 @MapperScan 注解,指定 Mapper接口的包路径

@MapperScantk.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 {@Autowiredprivate YourMapper yourMapper;public List<YourEntity> getAllEntities() {return yourMapper.selectAll();}// Add other methods as needed
}

二 对象和数据库记录映射

如果实体类的实例字段中包含对象,需要考虑如何对象数据库记录如何相互映射

通常情况下,使用 MyBatis 的 TypeHandler来处理对象字段的映射。

1.实体类(包含对象字段)

@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抽象类,创建一个 TypeHandler类来处理 Object对象字段的映射(对象与数据库字段的转换)。

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();@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, OtherObject parameter, JdbcType jdbcType) throws SQLException {// 设置 PreparedStatement 中的参数,将 OtherObject 对象转换为需要的类型try {ps.setObject(i, objectMapper.writeValueAsString(parameter));} catch (JsonProcessingException e) {throw new RuntimeException(e);}}@Overridepublic OtherObject getNullableResult(ResultSet rs, String columnName) throws SQLException {// 从 ResultSet 中获取数据并转换为 OtherObject 对象try {return objectMapper.readValue(rs.getString(columnName), OtherObject.class);} catch (JsonProcessingException e) {throw new RuntimeException(e);}}@Overridepublic OtherObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {// 从 ResultSet 中获取数据并转换为 OtherObject 对象try {return objectMapper.readValue(rs.getString(columnIndex), OtherObject.class);} catch (JsonProcessingException e) {throw new RuntimeException(e);}}@Overridepublic OtherObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {// 从 CallableStatement 中获取数据并转换为 OtherObject 对象try {return objectMapper.readValue(cs.getString(columnIndex), OtherObject.class);} catch (JsonProcessingException e) {throw new RuntimeException(e);}}
}

三 Example的应用

在 tk.mybatis 中,Example 类提供了一种便捷的方式来构建动态的 SQL 查询条件。
通过使用 Example 类,可以在不同的场景下动态地构建查询条件,而不需要手动编写复杂的 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 {@Autowiredprivate YourMapper yourMapper;/*** 根据 id 获取实体*/public YourEntity getEntity(String id) {// 1.创建 Example 对象Example example = new Example(YourEntity.class);// 2.创建 Criteria 对象,用于设置查询条件Example.Criteria criteria = example.createCriteria();// 3.设置查询条件criteria.andEqualTo("id", id);return yourMapper.selectOneByExample(example);}/*** 根据 name 获取实体*/public List<YourEntity> getEnties(String name) {// 1.创建 Example 对象Example example = new Example(YourEntity.class);// 2.创建 Criteria 对象,用于设置查询条件Example.Criteria criteria = example.createCriteria();// 3.设置查询条件criteria.andEqualTo("name", name);return yourMapper.selectByExample(example);}
}

Criteria 对象中可以添加不同的条件,比如 andEqualToandLikeandGreaterThan 等等,来实现更加灵活的查询。

四 分页

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) {// 设置分页参数PageHelper.startPage(pageNum, pageSize);// 执行查询List<YourEntity> entities = yourMapper.selectAll();// 获取分页信息PageInfo<YourEntity> pageInfo = new PageInfo<>(entities);log.info("{}", pageInfo.getPageNum());// 返回分页结果return pageInfo.getList();
}

pageNumpageSize,分别表示要查询的页码每页显示的记录数

通过 PageHelper.startPage 方法设置分页参数

查询结果会被自动分页,存储在 PageInfo 对象中,可以从中获取分页信息和当前页的数据列表。

2.RowBounds

RowBounds 是 MyBatis 提供的一种简单的分页实现方式,它通过在查询时指定起始行返回的最大行数来实现分页。

在 tk.mybatis 中,selectByRowBounds 方法可以直接在 Mapper 接口中使用,它接受两个参数:

  1. 查询条件(实体属性)
  2. RowBounds 对象
public List<YourEntity> pagingByRowBounds(int pageNum, int pageSize) {// 创建 PageRowBounds 对象,表示分页的起始行和每页显示的行数PageRowBounds pageRowBounds = new PageRowBounds((pageNum - 1) * pageSize, pageSize);// 执行分页查询,传入查询条件(实体属性)和 PageRowBounds 对象List<YourEntity> entities = yourMapper.selectByRowBounds(null, pageRowBounds);return entities;
}

创建 PageRowBounds 对象,设置起始行每页显示的行数

调用 yourMapper.selectByRowBounds 方法执行分页查询,传入了查询条件为 null(表示查询所有记录)和 PageRowBounds 对象。

在使用 selectByRowBounds 方法时,需要手动计算分页的起始行,并创建对应的 PageRowBounds 对象。

这种方式相对比较底层,需要更多的手动操作,但在某些情况下可能更加灵活。

这篇关于Spring Boot 集成 tk.mybatis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/928353

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.