5 、自动填充功能
有些时候我们可能会有这样的需求,插入或者更新数据时,希望有些字段可以自动填充数据,比如密码、version等。在MP中提供了这样的功能,可以实现自动填充。
5.1、添加@TableField注解
为password添加自动填充功能,在新增数据时有效。
FieldFill提供了多种模式选择:
5.2、编写MyMetaObjectHandler
[main] [cn.itcast.mp.mapper.UserMapper.findAll]-[DEBUG] ==> Preparing: select * from tb_user [main] [cn.itcast.mp.mapper.UserMapper.findAll]-[DEBUG] ==> Parameters: [main] [cn.itcast.mp.mapper.UserMapper.findAll]-[DEBUG] <== Total: 10
@TableField(fill = FieldFill.INSERT) //插入数据时进行填充 private String password;
public enum FieldFill { /** * 默认不处理 */ DEFAULT, /** * 插入时填充字段 */ INSERT, /** * 更新时填充字段 */ UPDATE, /** * 插入和更新时填充字段 */ INSERT_UPDATE }
package cn.itcast.mp.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;
@Component public class MyMetaObjectHandler implements MetaObjectHandler {
5.3、测试
结果:
6 、 逻辑删除
开发系统时,有时候在实现功能时,删除操作需要实现逻辑删除,所谓逻辑删除就是将数据标记为删除,而并非真正的物理删除(非DELETE操作),查询时需要携带状态条件,确保被标记的数据不被查询到。这样做的目的就是避免数据被真正的删除。
@Override public void insertFill(MetaObject metaObject) { Object password = getFieldValByName("password", metaObject); if(null == password){ //字段为空,可以进行填充 setFieldValByName("password", " 123456 ", metaObject); } }
@Override public void updateFill(MetaObject metaObject) { } }
@Test public void testInsert(){ User user = new User(); user.setName("关羽"); user.setUserName("guanyu"); user.setAge( 30 ); user.setEmail("guanyu@itast.cn"); user.setVersion( 1 );
int result = this.userMapper.insert(user); System.out.println("result = " + result); }
MP就提供了这样的功能,方便我们使用,接下来我们一起学习下。
6.1、修改表结构
为tb_user表增加deleted字段,用于表示数据是否被删除, 1 代表删除, 0 代表未删除。同时,也修改User实体,增加deleted属性并且添加@TableLogic注解:
6.2、配置
application.properties:
6.3、测试
执行的SQL:
ALTER TABLE `tb_user` ADD COLUMN `deleted` int( 1 ) NULL DEFAULT 0 COMMENT ' 1 代表删除, 0 代表未删除' AFTER `version`;
@TableLogic private Integer deleted;
# 逻辑已删除值(默认为 1 ) mybatis-plus.global-config.db-config.logic-delete-value= 1 # 逻辑未删除值(默认为 0 ) mybatis-plus.global-config.db-config.logic-not-delete-value= 0
@Test public void testDeleteById(){ this.userMapper.deleteById( 2 L); }
[main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] ==> Preparing: UPDATE tb_user SET deleted= 1 WHERE id=? AND deleted= 0 [main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] ==> Parameters: 2 (Long) [main] [cn.itcast.mp.mapper.UserMapper.deleteById]-[DEBUG] <== Updates: 1
测试查询:
执行的SQL:
可见,已经实现了逻辑删除。
7 、 通用枚举
解决了繁琐的配置,让 mybatis 优雅的使用枚举属性!
7.1、修改表结构
7.2、定义枚举
@Test public void testSelectById(){ User user = this.userMapper.selectById( 2 L); System.out.println(user); }
[main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] ==> Preparing: SELECT id,user_name,password,name,age,email,version,deleted FROM tb_user WHERE id=? AND deleted= 0 [main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] ==> Parameters: 2 (Long) [main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] <== Total: 0
ALTER TABLE `tb_user` ADD COLUMN `sex` int( 1 ) NULL DEFAULT 1 COMMENT ' 1 - 男, 2 - 女' AFTER `deleted`;
package cn.itcast.mp.enums; import com.baomidou.mybatisplus.core.enums.IEnum; import com.fasterxml.jackson.annotation.JsonValue;
public enum SexEnum implements IEnum<Integer> { MAN( 1 ,"男"),
7.3、配置
7.4、修改实体
7.5、测试
测试插入数据:
SQL: WOMAN( 2 ,“女”); private int value; private String desc;
SexEnum(int value, String desc) { this.value = value; this.desc = desc; }
@Override public Integer getValue() { return this.value; }
@Override public String toString() { return this.desc; } }
# 枚举包扫描 mybatis-plus.type-enums-package=cn.itcast.mp.enums private SexEnum sex; @Test public void testInsert(){ User user = new User(); user.setName("貂蝉"); user.setUserName("diaochan"); user.setAge( 20 ); user.setEmail("diaochan@itast.cn"); user.setVersion( 1 ); user.setSex(SexEnum.WOMAN);
int result = this.userMapper.insert(user); System.out.println("result = " + result); }
查询:
结果:
从测试可以看出,可以很方便的使用枚举了。
查询条件时也是有效的:
[main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] ==> Preparing: INSERT INTO tb_user ( user_name, password, name, age, email, version, sex ) VALUES ( ?, ?, ?, ?, ?, ?,? ) [main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] ==> Parameters: diaochan(String), 123456 (String), 貂蝉(String), 20 (Integer), diaochan@itast.cn(String), 1 (Integer), 2 (Integer) [main] [cn.itcast.mp.mapper.UserMapper.insert]-[DEBUG] <== Updates: 1
@Test public void testSelectById(){ User user = this.userMapper.selectById( 2 L); System.out.println(user); }
[main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] ==> Preparing: SELECT id,user_name,password,name,age,email,version,deleted,sex FROM tb_user WHERE id=? AND deleted= 0 [main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] ==> Parameters: 2 (Long) [main] [cn.itcast.mp.mapper.UserMapper.selectById]-[DEBUG] <== Total: 1
User(id= 2 , userName=lisi, password= 123456 , name=李四, age= 30 , email=test 2 @itcast.cn, address=null, version= 2 , deleted= 0 , sex=女)
SQL:
8 、代码生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper
XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
效果:
8.1、创建工程
pom.xml: @Test public void testSelectBySex() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("sex", SexEnum.WOMAN); List<User> users = this.userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } }
[main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] ==> Preparing: SELECT id,user_name,password,name,age,email,version,deleted,sex FROM tb_user WHERE deleted= 0 AND sex =? [main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] ==> Parameters: 2 (Integer) [main] [cn.itcast.mp.mapper.UserMapper.selectList]-[DEBUG] <== Total: 3
<?xml version=" 1. 0 " encoding="UTF- 8 "?> <project xmlns="http://maven.apache.org/POM/ 4. 0. 0 " xmlns:xsi="http://www.w 3 .org/ 2001 /XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/ 4. 0. 0 http://maven.apache.org/xsd/maven- 4. 0. 0 .xsd"> <modelVersion> 4. 0. 0 </modelVersion>
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version> 2. 1. 4 .RELEASE</version> </parent>
<groupId>cn.itcast.mp</groupId> <artifactId>itcast-mp-generator</artifactId> <version> 1. 0 - SNAPSHOT</version>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
<!--mybatis-plus的springboot支持--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version> 3. 1. 1 </version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version> 3. 1. 1 </version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version> 5. 1. 47 </version> </dependency> <dependency> <groupId>org.slf 4 j</groupId> <artifactId>slf 4 j-log 4 j 12 </artifactId> </dependency>
</dependencies> <build>
8.2、代码
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
</project> package cn.itcast.mp.generator; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.FileOutConfig; 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.TemplateConfig; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/** * <p> * mysql 代码生成器演示例子 * </p> */ public class MysqlGenerator { /** * <p> * 读取控制台内容 * </p> */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); }
/** * RUN THIS */ public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator();
// 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("itcast"); gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql:// 127. 0. 0. 1 : 3306 /mp? useUnicode=true&useSSL=false&characterEncoding=utf 8 "); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模块名")); pc.setParent("cn.itcast.mp.generator"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return projectPath + "/itcast-mp- generator/src/main/resources/mapper/" + pc.getModuleName()
8.3、测试
代码已生成:
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("com.baomidou.mybatisplus.samples.generator.common.BaseE ntity"); strategy.setEntityLombokModel(true); // strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.B aseController"); strategy.setInclude(scanner("表名")); strategy.setSuperEntityColumns("id"); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有! mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
实体对象:
9 、MybatisX 快速开发插件
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。
安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装。
功能:
Java 与 XML 调回跳转
Mapper 方法自动生成 XML