本文为SpringBoot整合MyBatis-Plus的基本增删查改,条件查询,分页查询,SQL日志配置及代码生成器相关的开发笔记
快速开始 | MyBatis-Plus (baomidou.com)
com.baomidou
mybatis-plus-boot-starter
3.5.1
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
//自动生成id,雪花算法
@TableId(type = IdType.ASSIGN_ID)
private Integer id;
private String name;
private String password;
//乐观锁
@Version
private Integer version;
//创建时间,在插入时自动填充
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
//更新时间,在插入与更新时自动填充
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
//逻辑删除
@TableLogic
private Integer deleted;
}
//继承BaseMapper
@Repository
public interface UserMapper extends BaseMapper {
}
@Configuration
public class MybatisConfiguration {
//注册插件主体到IOC容器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加乐观锁拦截器
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
// 配置@TableField(fill = FieldFill.INSERT)注解,插入时填充
@Override
public void insertFill(MetaObject metaObject) {
// MetaObjectHandler setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
//fieldName方法名,fieldVal填充值
this.setFieldValByName("gmtCreate",new Date(),metaObject);
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
// 配置 @TableField(fill = FieldFill.INSERT_UPDATE)注解,插入与更新时填充
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified",new Date(),metaObject);
}
}
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启日志
global-config:
db-config:
logic-delete-value: 1 #逻辑删除值
logic-not-delete-value: 0 #未被逻辑删除值
@Autowired
private UserMapper userMapper;
@Test
public void selectTest() {
//遍历全表,参数为QueryWrapper,这里不需要暂时填写null
List users = userMapper.selectList(null);
users.forEach(System.out::println);
}
@Test
public void insertTest() {
User user = new User();
user.setName("test");
user.setPassword("123456");
//这里id使用了自动填充
userMapper.insert(user);
}
查看结果:
可以看到Version已经设为默认值1,自动填充的日期也成功实现
@Test
public void updateTest() {
//根据id查询user对象
User user = userMapper.selectById(1);
user.setName("test1");
//更新
userMapper.updateById(user);
}
@Test
public void deleteTest() {
//将要删除的信息放到map里
Map userHashMap = new HashMap<>();
userHashMap.put("id", 1);
userMapper.deleteByMap(userHashMap);
}
@Test
public void wrapperTest(){
QueryWrapper wrapper = new QueryWrapper<>();
//配置wrapper条件,详细的条件函数在官方文档中有
wrapper.isNotNull("id")
.eq("id",1);
userMapper.selectList(wrapper).forEach(System.out::println);
}
在配置类中加上
@Configuration
public class MybatisConfiguration {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
@Test
public void pageTest(){
// public Page(long current, long size)
//current当前页,size每页的大小
Page userPage = new Page<>(1,3);
userPage = userMapper.selectPage(userPage, null);
userPage.getRecords().forEach(System.out::println);
}
p6spy
p6spy
3.9.1
将数据库驱动设为com.p6spy.engine.spy.P6SpyDriver
url前缀改为jdbc:p6spy:mysql:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:mysql://localhost:3306/...
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准
outagedetectioninterval=1
com.baomidou
mybatis-plus-generator
3.5.1
org.freemarker
freemarker
2.3.31
io.springfox
springfox-boot-starter
3.0.0
新建测试类
public class CodeGenerate {
@Test
public void generateCode(){
FastAutoGenerator.create("jdbc:p6spy:mysql://localhost:3306/...",
"数据库账户", "密码")
.globalConfig(builder -> {
builder.author("test") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir(System.getProperty("user.dir")+"/src/main/java");
// 指定输出目录为工程目录
})
.packageConfig(builder -> {
builder.parent("com.test") // 设置父包名
.moduleName("module01") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir")+"/src/main/resources/mapper")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("user") // 设置需要生成的表名,可为多个
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
生成完毕后,运行时swagger如出现 Failed to start bean 'documentationPluginsBootstrapper'; 错误
在配置文件中加上
Spring.mvc.pathmatch.matching-strategy=ant_path_matcher