当前位置: 代码网 > it编程>编程语言>Java > SpringBoot集成tk.mybatis实践

SpringBoot集成tk.mybatis实践

2026年04月24日 Java 我要评论
一 spring boot 集成 tk.mybatistk.mybatis 是 mybatis 的一个插件,用于简化 mybatis 的开发。1.添加依赖spring boot 项目中的 pom.xm

一 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.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.创建实体类

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

@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 {

    @autowired
    private 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();

    @override
    public 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);
        }
    }

    @override
    public 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);
        }
    }

    @override
    public 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);
        }
    }

    @override
    public 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 {

    @autowired
    private 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 对象。

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com