Java实战 (Mybtis-Plus基础设置) 4
简介
1.在我们对数据库进行增删改查的时候,往往需要按照一定的规范。就比如阿里的规范,数据库中的表需要有 gmt_Create、gmt_Modified 等字段,那么我们在编写实体类的时候会有大量的重复代码,这时候我们需要一个基础的实体类,让我们后面要定义的实体类都继承该类,使得我们实体类代码减少。往往这些字段需要程序自动维护,Mybatis-Plus也提供了该功能。
2.在一些情况下,我们需要伪删除,Mybatis-Plus已经提供了该功能,我们只需要少许的配置即可。
3.Mybatis-Plus支持分页功能,我们只需要在配置类中将该功能打开即可。
4.Mybatis-Plus可以读取数据库表信息,自动生成代码骨架减少开发时间
代码示例
1. Mybatis-Plus配置
1.1 依赖引入
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
</dependency>
1.2 配置文件
spring:
datasource: # mysql 数据库连接
url: jdbc:mysql://192.168.10.30:3306/sevattal_backuser?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false&useUnicode=true&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: sevattal
password: Lovemomo
# mybatis 配置项目打包时 mapper.xml的路径
# mybatis 配置日志
mybatis-plus:
mapperLocations: classpath:com/sevattal/service/edu/mapper/xml/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2. 基础实体类参考
2.1 基础实体类
@TableField(fill = FieldFill.INSERT): 注解表示在插入该条数据的时候,这个字段能够自动生成
@TableField(fill = FieldFill.INSERT_UPDATE): 注解表示在修改该条数据的时候,这个字段能够自动生成
package com.sevattal.service.base.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "ID")
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime gmtModified;
}
2.2 继承基础实体类
@TableLogic: 表示该字段用来管理逻辑删除
package com.sevattal.service.backuser.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.sevattal.service.base.model.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableLogic;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 后台用户表
* </p>
*
* @author Sevattal
* @since 2021-04-20
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@ApiModel(value="BackuserUser对象", description="后台用户表")
public class BackuserUser extends BaseEntity {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "登录用户名")
private String username;
@ApiModelProperty(value = "用户昵称")
private String nickname;
@ApiModelProperty(value = "邮箱号")
private String email;
@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "默认图片地址")
private String imageUrl;
@ApiModelProperty(value = "排序")
private Integer sort;
@ApiModelProperty(value = "是否禁用 1(true)已禁用, 0(false)未禁用")
@TableField("is_disabled")
private Boolean disabled;
@ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
@TableField("is_deleted")
@TableLogic
private Boolean deleted;
}
3. Mybatis-Plus开启分页功能
3.1 MyBatis-Plus配置类**
package com.sevattal.service.base.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author Sevattal
**/
@EnableTransactionManagement
@Configuration
@MapperScan("com.sevattal.service.*.mapper")
public class MybatisPlusConfig {
/*
* 分页插件
*
* */
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
3.2 在 Controller 层进行分页返回数据(这边只演示在Controller层如何操作)
@ApiOperation("获取后台用户列表")
@GetMapping("get-list/{page}/{limit}")
public R getBackUserList(
@ApiParam(value="页码",required= true) @PathVariable Long page,
@ApiParam(value="每页记录数",required = true) @PathVariable Long limit,
@ApiParam("查询条件") BackuserUserSeachVo backuserUserSeachVo){
System.out.println("page: " + page + "limit: " + limit + "BackuserUserSeachVo:" + backuserUserSeachVo);
Page<BackuserUser> pageParam = new Page<>(page,limit);
IPage<BackuserUser> pageModel = backuserUserService.selectPage(pageParam,backuserUserSeachVo);
List<BackuserUser> records = pageModel.getRecords();
long total = pageModel.getTotal();
return R.ok().data("total",total).data("userList",records);
}
4. Mybatis-Plus 代码生成器参考
package com.sevattal.service.background_user;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
/**
* @author Sevattal
* @date 2020/6/22 21:06
* mybatis 代码生成器
**/
public class CodeGenerator {
@Test
public void genCode() {
String dbName = "sevattal_backuser";
String prefix = "sevattal_";
String moduleName = "backuser";
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("Sevattal");
gc.setOpen(true); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ASSIGN_ID); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(true);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.10.30:3306/" + dbName +
"?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("sevattal");
dsc.setPassword("Lovemomo");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(moduleName); //模块名
pc.setParent("com.sevattal.service");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名
strategy.setTablePrefix(prefix + "_");//设置表前缀不生成
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true)
strategy.setLogicDeleteFieldName("is_deleted");//逻辑删除字段名
strategy.setEntityBooleanColumnRemoveIsPrefix(true);//去掉布尔值的is_前缀
//自动填充
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
//设置BaseEntity
strategy.setSuperEntityClass("com.sevattal.service.base.model.BaseEntity");
// 填写BaseEntity中的公共字段
strategy.setSuperEntityColumns("id", "gmt_create", "gmt_modified");
// 6、执行
mpg.execute();
}
}