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

整合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

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...