一、MyBatisPlus介绍
二、MyBatisPlus使用
2.1 添加依赖
- swagger2
- lombok
- MyBatisPlus里面集成了MyBatis 所以不用再加MyBatis依赖 否则容易报错
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.1 启动类添加注解
@MapperScan(“com.xu.mapper”)
2.1 application.properties
# 设置开发环境(使用性能分析插件要求为开发或测试环境)
spring.profiles.active=dev
# 端口号
spring.port-=9090
# 数据库连接配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置日志 控制台输出sql语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
2.2 添加BatisPlusConfig配置类
@MapperScan("com.kuang.mapper") // 扫描我们的 mapper 文件夹
@EnableTransactionManagement // 启动事务管理(乐观锁)
@Configuration // 配置类
public class MyBatisPlusConfig {
// 注册乐观锁插件
//对应version属性添加注解@Version
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
// 逻辑删除组件
//实体类中属性添加注解@TableLogic
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
//SQL执行效率插件
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // 设置sql执行的最大时间,如果超过了则不执行
performanceInterceptor.setFormat(true); //是否开启代码格式化(更好读sql语句)
return performanceInterceptor;
}
}
2.3 添加MyMetaObjectHandler自动填充`配置类
- 实体类字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
- 添加配置类
@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
// setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
2.4 代码自动生成器
- 新建一个AutoGenerator 类
- 策略配置 中修改想要生成的表名
- 执行此类即可
// 代码自动生成器
public class AutoGenerator {
public static void main(String[] args) {
// 需要构建一个 代码自动生成器 对象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("许久龙");
gc.setOpen(false); //生成完是否打开资源管理器
gc.setFileOverride(false); // 是否覆盖原文件
gc.setServiceName("%sService"); // 去Service的I前缀
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE); //注释的日期格式只显示时间
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community?
useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL); //驱动类型
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.kuang");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
// 设置要映射的表名
strategy.setInclude("blog_tags","course","links","sys_settings","user_record"," user_say");
strategy.setNaming(NamingStrategy.underline_to_camel); //下划线转驼峰
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自动lombok;
strategy.setLogicDeleteFieldName("deleted"); //开启逻辑删除字段
// 自动填充配置
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.setVersionFieldName("version");
strategy.setRestControllerStyle(true); //Restful风格的Controller
strategy.setControllerMappingHyphenStyle(true); // 开启下划线命名 如localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //执行
}
}
三、主键生成策略
- 在id属性上添加注解@TableId(type = IdType.AUTO)
// 对应数据库中的主键 (uuid、自增id、雪花算法、redis、zookeeper!)
@TableId(type = IdType.AUTO)
private Long id;
- 数据库表id字段开启
自增
四、自动填充策略(具体看上面2.3)
- 删除数据库创建时间、修改时间字段的默认值
- 实体类字段属性上需要增加注解
- 添加配置类
五、乐观锁
-
乐观锁实现方式:
取出记录时,获取当前 version
更新时,带上这个 version
执行更新时, set version = newVersion where version = oldVersion
如果 version 不对,就更新失败 -
给数据库中增加version字段!设置默认值为1
-
实体类加对应的字段并加注解@Version
@Version
private Integer version;
- 配置类里添加乐观锁组件
六、分页查询
- 配置类里添加分页组件
- 使用
// 测试分页查询
@Test
public void testPage(){
// 参数一:当前页
// 参数二:页面大小
Page<User> page = new Page<>(2,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
//计算总数据数
System.out.println(page.getTotal());
}
七、逻辑删除
- 数据库表中添加字段deleted 设置默认值为0 (0 正常 1 删除)
- 实体类中增加属性并添加注解@TableLogic
@TableLogic //逻辑删除
private Integer deleted;
- 配置类里添加逻辑删除组件
- yml/propertied文件添加配置
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
八、性能分析插件
- 配置类里添加性能分析组件
- 在SpringBoot中配置环境为dev或者 test 环境
九、条件构造器
@Test
void contextLoads() {
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println);
}
@Test
void test2(){
// 查询名字狂神说
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","狂神说");
User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List或者 Map
System.out.println(user);
}
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}
// 模糊查询
@Test
void test4(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
// 模糊查询
@Test
void test5(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// id 在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
// 模糊查询
@Test
void test6(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 通过id进行排序
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}