Spring Boot 集成 MyBatis, 分页插件 PageHelper, 通用 Mapper

Spring Boot 集成 MyBatis, 分页插件 PageHelper, 通用 Mapper

配置

  • pom依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>1.2.4</version>
</dependency>
<!--pagehelper-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
  • application配置
#mybatis
mybatis.type-aliases-package=tk.mybatis.springboot.model
mybatis.mapper-locations=classpath:mapper/*.xml

#mapper
#mappers 多个接口时逗号隔开
mapper.mappers=tk.mybatis.springboot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL

#pagehelper
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
  • application.yml 配置
mybatis:
    type-aliases-package: tk.mybatis.springboot.model
    mapper-locations: classpath:mapper/*.xml

mapper:
    mappers:
        - tk.mybatis.springboot.util.MyMapper
    not-empty: false
    identity: MYSQL

pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
  • 创建一个通用接口
//接口名随意
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
    //TODO
    //FIXME 特别注意,该接口不能被扫描到,否则会出错
}
  • mapper层配置

    注意:entity与数据表必须对应,否则会报错

@Mapper
public interface UserMapper extends MyMapper<User> {//实现自定义的接口
}
  • entity层配置
  1. entity类必须与数据库表同名或与驼峰形式对应;
  2. entity参数必须与数据表字段对应;
  3. 需要在entity上添加属性时,不能修改原始entity,需要重新创建一个entity继承原entity;增删改功能可以直接使用新entity,查询时返回的数据表对应的entity类型必须是原entity类型,若想转为新的entity,需要自己转换比如
List<子> tab2s = JSONArray.parseArray(JSON.toJSONString(tab1s), 子.class);

注意:当entity中添加其他参数时,调用增删改查方法都会异常,因为增删改查是以entity为基础的;在mapper层继承MyMapper时填入了entity,entity变化会引起对应SQL语句变化,会导致调用数据库异常.

调用

  • 基本增删改查

1547712353544

1547712369629

1547712384613

1547712397040

  • 复杂查询
Example example=new Example(User.class);
example.setOrderByClause("id DESC");
Example.Criteria criteria=example.createCriteria();
criteria.andIsNotNull("id");
userMapper.selectByExample(example);




posted @   紫月java  阅读(368)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示