Mybatisplus:一些常用功能
自动驼峰
mybatis-plus:configuration:# 开启驼峰命名规则,默认true开启map-underscore-to-camel-case: true# 控制台日志打印,便于查看SQLlog-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@TableName
作用:表名注解,标识实体类对应的表,如果表名和类名一致可以省略
使用位置:实体类
@TableName("tbl_product") //绑定表关系
public class Product {}如果每个表都是以固定前缀开头,可以全局配置表前缀
属性设置 > 全局设置: 如果使用了 @TableName 指定表名,则会忽略全局的表前缀
mybatis-plus:global-config:db-config:table-prefix: tbl_ #表前缀
@TableField
属性 类型 默认值 描述 value String "" 数据库字段名,如果同名可以省略 exist boolean true 是否为数据库表字段,如果表中没有该字段必须设置为false,CRUD都不会包含该字段 fill Enum FieldFill.DEFAULT 字段自动填充策略,默认不会自动填充值 // 商品详细信息字段(详情表) 排除跟商品信息表映射关系 @TableField(exist = false) private String desc;
@TableId
//IdType 指定主键类型 @TableId(value = "id",type = IdType.AUTO) private Long id;
值 描述 NONE 默认值
相当于INPUT+ASSIGN_IDAUTO 数据库主键自增 INPUT 手动设置主键值 ASSIGN_ID 主键对应的类型可以是数字类型或者数字类型的字符串 由java客户端,底层基于雪花算法,生成的唯一主键 ASSIGN_UUID 生成的主键值包含数字和字母组成的字符串 UUID
示例:b463ec84690de187e3f9ad9229327d15如果大部分表主键都是自增,可以进行全局设置
属性上的优先级 > 全局设置
mybatis-plus:global-config:db-config:id-type: auto #主键策略table-prefix: tbl_ #表前缀
自动填充
自动填充字段 | MyBatis-Plus
@TableField(fill = FieldFill.INSERT) private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE) private Date lastUpdateTime;
配置类
package com.itheima.mp.config;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;import java.util.Date;@Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {log.info("start insert fill ....");this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)this.strictInsertFill(metaObject, "lastUpdateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)}@Overridepublic void updateFill(MetaObject metaObject) {log.info("start update fill ....");this.strictUpdateFill(metaObject, "lastUpdateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐)} }
逻辑删除实际上就是一个修改操作
@TableLogic private Integer deleted;
分页插件:官网分页插件
配置类
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;// MP配置类 @Configuration public class MybatisPlusConfig {// MyBatisPlust拦截器配置@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 添加分页插件拦截器interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}}
Ipage
@GetMapping("/{page}/{pageSize}") public IPage<Product> Page(@PathVariable("pageNo") Long page,@PathVariable("pageSize") Long pageSize) {IPage<Product> ipage = new Page<>(page,pageSize);ipage = productService.page(ipage);return ipage;}