SpringBoot集成通用Mapper和分页插件PageHelper(一)

  通用 Mapper 是一个可以实现任意 MyBatis 通用方法的框架,项目提供了常规的增删改查操作以及Example 相关的单表操作。通用 Mapper 是为了解决 MyBatis 使用中 90% 的基本操作,使用它可以很方便的进行开发,可以节省开发人员大量的时间。注意这个框架只适合单表操作,实现了单表的基本增删改查操作,对于多表操作,还是需要自己实现xml,项目文档可以参考github上面的文档(GitHub文档 | 官方文档)接下来就开始整合。 1. 环境准备   示例demo使用的是MySQL数据库,最低版本要求5.7

create database test001 default CHARACTER SET UTF8MB4 collate utf8mb4_general_ci;use test001;drop table if exists user;drop table if exists role;create table user( id varchar(255) primary key comment ‘主键ID’, user_name varchar(255) not null comment ‘用户名’, password varchar(255) not null comment ‘密码’, email varchar(255) comment ‘邮箱’, role_id varchar(255) comment ‘角色ID’) comment ‘用户表’;create table role( id varchar(255) primary key comment ‘主键ID’, role_name varchar(255) not null comment ‘角色名’) comment ‘角色表’;

2. 导入jar包   为了方便,这里将需要用上的jar都列举在这里,其中,通用mapper已经集成了MyBatis,所以可以不用重复引入;相反如果你引入了通用mapper和MyBatis两个starter,那么MyBatis官方的自动配置不会生效。

com.github.pagehelper pagehelper-spring-boot-starter 1.4.1 org.projectlombok lombok 1.18.22 org.mybatis.generator mybatis-generator-core 1.4.1 com.oracle.database.jdbc ojdbc8 21.5.0.0 mysql mysql-connector-java 8.0.21 tk.mybatis mapper-spring-boot-starter 4.2.1 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test

3. 配置   MyBatis的配置就不在多说了,这里主要说说通用mapper的配置,相关配置参数可以查看 tk.mybatis.mapper.entity.Config 类

spring: # 数据源配置 datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.1.8.41:3306/test001 username: root password: 123456# mybatis 配置mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.hxz.entity configuration: map-underscore-to-camel-case: true # 驼峰命名 cache-enabled: true # 开启二级缓存 lazy-loading-enabled: true # 懒加载,分布查询时需要开启 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出# 通用mapper 配置mapper: not-empty: true # 判断字符串类型 != ”

4. mapper 接口声明   mapper接口需要继承通用mapper的 tk.mybatis.mapper.common.Mapper 类,该类提供了大量的通用接口

public interface RoleMapper extends tk.mybatis.mapper.common.Mapper { }

5. mapper 接口扫描   使用 tk.mybatis.spring.annotation.MapperScan 扫描,注意不是mybatis的MapperScan

// 使用 tk.mybatis.spring.annotation.MapperScan 扫描,注意不是mybatis的MapperScan@tk.mybatis.spring.annotation.MapperScan(basePackages = “包名”)public class SpringbootMybatisMapperApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMybatisMapperApplication.class, args); }}

  通过mapper同样是支持MyBatis的原生功能,这里就不在详细说明了

  源码地址:https://gitee.com/peachtec/hxz-study


比丘资源网 » SpringBoot集成通用Mapper和分页插件PageHelper(一)

发表回复

提供最优质的资源集合

立即查看 了解详情