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

相关内容

热门资讯

a股有几家上市公司 中国a股上... 齐鲁晚报讯祁鲁镇记者张通讯员6月15日,中国证监会山东监管局连续发布3份辅导工作总结报告,其中2份的...
开办小型日化厂违法吗 小型洗洁... 食品安全一直受到关注,尤其是在这样的大热天,人们对进口的东西更加谨慎。抚顺的朋友们,你们可能已经注意...
马云预言未来十大行业 暴利行业... 说到马云,很多人都很熟悉他。马云通过自己的努力和奋斗,逐渐开创了网上支付,他的眼光和勇气是非常独特的...
总是很自卑怎么办?做什么都做不... 总是很自卑怎么办?做什么都做不好,心态也很不好,感觉真的好累自卑跟性格有很大关系!你可能有些内向!其...
求一部国外电影,关于博物馆的故... 求一部国外电影,关于博物馆的故事讲的是在一个博物馆里每到晚上里面的东西就会复活,好像恐龙骨架什么的,...
我愿做江州司马为你泪湿青衫 我愿做江州司马为你泪湿青衫《琵琶行》白居易 座中泣下谁最多,江州司马青衫湿。同是天涯沦落人,相逢...
肩周炎怎么治? 肩周炎怎么治?肩周炎又称冻结肩、五十肩,是肩关节周围软组织慢性炎症性病变,主要以保守治疗为主。具体治...
谁有古代言而无信的例子? 谁有古代言而无信的例子?谁有古代言而无信的例子? 秦惠文王、张仪:秦惠文王更元十二年(前313年...
学生成长记录手册上家长寄语怎么... 学生成长记录手册上家长寄语怎么写可以写的抒情点,如“在生活中的每一天,都是一个阳光明媚的日子,因为,...
和伴侣在一起时会做哪些事情? 和伴侣在一起时会做哪些事情?情侣刚在一起的时候总是想把自己好的一面展现给对方,但是随着时间长了,感情...