整合MyBatis-Plus
创始人
2024-05-30 06:43:52

整合MyBatis-Plus

  • 1、依赖
  • 2、配置文件
  • 3、启动类
  • 4、实体类
  • 5、Mapper
  • 6、主键策略
    • 6.1、ID_WORKER
    • 6.2、自增策略
    • 6.3、CURD测试
  • 7、条件构造器
  • 8、MyBatis-Plus封装service层
    • 8.1、添加service接口
    • 8.2、添加service接口实现
    • 8.3、测试service接口
  • 9、分页插件
    • 9.1、配置分页插件
    • 9.2、分页controller
    • 9.3、配置日期时间格式

1、依赖

com.baomidoumybatis-plus-boot-starter3.4.1

2、配置文件

配置 MySQL 数据库的相关配置及Mybatis-Plus日志

application.yml

spring:application:name: service-oaprofiles:active: dev

application-dev.yml

server:port: 8800
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 查看日志global-config:db-config:logic-delete-value: 1logic-not-delete-value: 0
spring:datasource:type: com.zaxxer.hikari.HikariDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/guigu-oa?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8username: rootpassword: 12345

3、启动类

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹

package com.atguigu;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@ComponentScan("com.atguigu")
@MapperScan("com.atguigu.*.mapper")
public class ServiceAuthApplication {public static void main(String[] args) {SpringApplication.run(ServiceAuthApplication.class, args);}}

4、实体类

package com.atguigu.model.system;import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.atguigu.model.base.BaseEntity;
import lombok.Data;@Data
@TableName("sys_role")
public class SysRole extends BaseEntity {private static final long serialVersionUID = 1L;//角色名称@TableField("role_name")private String roleName;//角色编码@TableField("role_code")private String roleCode;//描述@TableField("description")private String description;}

5、Mapper

com.baomidou.mybatisplus.core.mapper.BaseMapper这是Mybatis-Plus提供的默认Mapper接口

package com.atguigu.auth.mapper;import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface SysRoleMapper extends BaseMapper {}

6、主键策略

6.1、ID_WORKER

MyBatis-Plus默认的主键策略是:ID_WORKER 全局唯一ID

6.2、自增策略

要想主键自增需要配置如下主键策略

  • 需要在创建数据表的时候设置主键自增
  • 实体字段中配置 @TableId(type = IdType.AUTO)
@TableId(type = IdType.AUTO)
private Long id;

其它主键策略:分析 IdType 源码可知

public enum IdType {/*** 数据库ID自增*/AUTO(0),/*** 该类型为未设置主键类型*/NONE(1),/*** 用户输入ID* 该类型可以通过自己注册自动填充插件进行填充*/    INPUT(2),/*** 全局唯一ID*/    ASSIGN_ID(3),/*** 全局唯一ID (UUID)*/ASSIGN_UUID(4),/** @deprecated */@DeprecatedID_WORKER(3),/** @deprecated */@DeprecatedID_WORKER_STR(3),/** @deprecated */@DeprecatedUUID(4);private final int key;private IdType(int key) {this.key = key;}public int getKey() {return this.key;}
}

6.3、CURD测试

int result = sysRoleMapper.insert(sysRole);
System.out.println(result); //影响的行数
System.out.println(sysRole); //id自动回填int result = sysRoleMapper.updateById(sysRole);
System.out.println(result);/*** application-dev.yml 加入配置* 此为默认值,如果你的默认值和mp默认的一样,则不需要该配置* mybatis-plus:*   global-config:*     db-config:*       logic-delete-value: 1*       logic-not-delete-value: 0*/
int result = sysRoleMapper.deleteById(2L);
System.out.println(result);int result = sysRoleMapper.deleteBatchIds(Arrays.asList(1, 1));
System.out.println(result);

7、条件构造器

LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRole::getRoleCode, "role");
List users = sysRoleMapper.selectList(queryWrapper);
System.out.println(users);

8、MyBatis-Plus封装service层

8.1、添加service接口

com.baomidou.mybatisplus.extension.service.IService这是Mybatis-Plus提供的默认Service接口

package com.atguigu.auth.service;import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.extension.service.IService;import java.util.List;public interface SysRoleService extends IService {}

8.2、添加service接口实现

com.baomidou.mybatisplus.extension.service.impl.ServiceImpl这是Mybatis-Plus提供的默认Service接口实现

package com.atguigu.auth.service.impl;import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.model.auth.SysRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;import java.util.List;public class SysRoleServiceImpl extends ServiceImpl implements SysRoleService {}

8.3、测试service接口

//UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper
//所以不填写就是无任何条件
List users = sysRoleService.list();
users.forEach(System.out::println);boolean result = sysRoleService.save(sysRole);
System.out.println(result); //影响的行数
System.out.println(sysRole); //id自动回填boolean result = sysRoleService.updateById(sysRole);
System.out.println(result);boolean result = sysRoleService.removeById(2L);
System.out.println(result);LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.ge(SysRole::getRoleCode, "role");
List users = sysRoleService.list(queryWrapper);
System.out.println(users);

9、分页插件

9.1、配置分页插件

我们将@MapperScan(“com.atguigu.auth.mapper”)提取到该配置类上面,统一管理,启动类和yaml配置文件就不需要了

package com.atguigu.common.config.mp;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@MapperScan("com.atguigu.auth.mapper")
public class MybatisPlusConfig {/*** 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)*/@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}@Beanpublic ConfigurationCustomizer configurationCustomizer() {return configuration -> configuration.setUseDeprecatedExecutor(false);}
}

9.2、分页controller

//条件分页查询
//page 当前页  limit 每页显示记录数
//SysRoleQueryVo 条件对象
@ApiOperation("条件分页查询")
@GetMapping("{page}/{limit}")
public Result pageQueryRole(@PathVariable Long page,@PathVariable Long limit,SysRoleQueryVo sysRoleQueryVo) {//调用service的方法实现//1 创建Page对象,传递分页相关参数//page 当前页  limit 每页显示记录数Page pageParam = new Page<>(page,limit);//2 封装条件,判断条件是否为空,不为空进行封装LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();String roleName = sysRoleQueryVo.getRoleName();if(!StringUtils.isEmpty(roleName)) {//封装 like模糊查询wrapper.like(SysRole::getRoleName,roleName);}//3 调用方法实现IPage pageModel = sysRoleService.page(pageParam, wrapper);return Result.ok(pageModel);
}

9.3、配置日期时间格式

  jackson:date-format: yyyy-MM-dd HH:mm:sstime-zone: GMT+8

相关内容

热门资讯

容大感光:泰国基地规划进度、对... 投资者提问:东南亚 PCB 产能持续扩张,日系厂商在当地占据主导地位。公司泰国生产基地规划的油墨与干...
国家电网、南方电网达成我国首笔... (来源:电力国际汇epintl)按照国家发展改革委、国家能源局部署,6月18日,国家电网、南方电网达...
以军:打死扎扎和萨法迪!内塔尼... 据新华社,以色列国防军22日发表声明说,20日在加沙地带打死了两名巴勒斯坦伊斯兰抵抗运动(哈马斯)军...
浙江金华乡村“慢生活”吸引城市... 来源:中国新闻网 风铃祈福、夜间音乐会、农耕摸鱼体验......端午假期,在浙江金华经济技术开发区,...
画面公布:日本舰机滋扰挑衅,辽... 辽宁舰编队专业稳妥处置应对日本舰机滋扰挑衅6月22日,海军辽宁舰编队圆满完成远海实战化训练,安全顺利...