MybatisPlus相关操作
分页插件
1.配置类添加插件
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
2.查询操作
IPage<Student> page = new Page<>(1, 2);
//第一页,每页两条数据
IPage<Student> studentPage = studentService.page(page, Wrappers.<Student>lambdaQuery().eq(Student::getSex, true));
利用构造器查询操作
List<Student> studentList = studentService.list(Wrappers.<Student>lambdaQuery());
链接: 跟随条件规则.
对查询后的list分组
学生根据年龄进行分组
Map<Integer, List<Student>> map = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
只查询筛选字段
1.查询需要字段
blacklistService.list(Wrappers.<Blacklist>lambdaQuery().select(Blacklist.class, x -> x.getColumn().equals("user_name")));
blacklistService.list(Wrappers.<Blacklist>lambdaQuery().select(Blacklist::getUserName,Blacklist::getCreateTime));
2忽略字段
注意:主键无论如何都会查询出来,如果使用fastJson,可以通过JSONField(serialize = false)来忽略不返回给前台
blacklistService.list(Wrappers.<Blacklist>lambdaQuery().select(Blacklist.class, x -> !x.getColumn().equals("id") && !x.getColumn().equals("user_id"))));
逻辑删除
配置yml:
mybatis-plus.global-config.db-config.logic-delete-field=extend1
#指定逻辑删除字段
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
原理
SELECT id,user_name FROM blacklist WHERE extend1=‘0’
WHERE extend1=‘0’ 为mp自己拼接
注意
该字段数据库应该设置默认值为未删除,此时对应配置文件为0,因为测试插入数据,mp并不会为该字段赋值,删除时会赋值为1。
注解sql
基本sql
@Select(“select count(is_locked) from app_user where id = #{id}”)
Integer select(Integer id);
连表查询 ChildVO为自定义封装对象,包含phone和name两个属性
@Select(“select au.phone , a.name from app_user au ,animal a where a.id = au.id”)
List select1();
分页查询//传入其他sql实现分页连表查询
@Select(“select * from app_user where id > #{id}”)
Page selectPage(Page page, Integer id);
测试:
Page page = new Page<>(2, 3);
System.err.println(testMapper.selectPage(page, 3).getRecords());
构造器查询
@Select(“select * from app_user ${ew.customSqlSegment}”)
Page selectList(Page page, @Param(“ew”) Wrapper queryWrapper);
对构造器查询的测试:
Page objectPage = new Page<>(1, 10);
QueryWrapper objectQueryWrapper = new QueryWrapper<>();
objectQueryWrapper.lambda().eq(AppUser::getId, 2);
System.err.println(testMapper.selectList(objectPage, objectQueryWrapper).getRecords());
性能分析插件
1.引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--性能分析插件依赖-->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
2.添加配置文件spy.properties
和application.properties同级目录
# 3.2.1以上使用
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
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
driverlist=com.mysql.cj.jdbc.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
3.修改数据库配置
#数据源配置
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/asset_new?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
#spring.datasource.username=root
#spring.datasource.password=123456
#p6spy 性能分析插件
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/asset_new?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
4.执行即可
加解密数据库数据
1.继承BaseTypeHandler
/**
* @Author: GQS
* @Description: 进行数据处理,这里对数据进行加密
* @Date: 2021/12/28 15:25
*/
public class DataEncryptHandler extends BaseTypeHandler {
String AESKey = "aaaabbbbccccdddd";
@SneakyThrows
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, EncyptUtil.aesEncrypt((String) o, AESKey));
}
@SneakyThrows
@Override
public Object getNullableResult(ResultSet resultSet, String s) {
return EncyptUtil.aesDecrypt(resultSet.getString(s), AESKey);
}
@SneakyThrows
@Override
public Object getNullableResult(ResultSet resultSet, int i) {
return EncyptUtil.aesDecrypt(resultSet.getString(i), AESKey);
}
@SneakyThrows
@Override
public Object getNullableResult(CallableStatement callableStatement, int i) {
return EncyptUtil.aesDecrypt(callableStatement.getString(i), AESKey);
}
}
2.实体类加注解
1.在 @TableName 注解中,设置 autoResultMap 参数为true
2.在需要加解密的字段上,添加注解 @TableField(typeHandler = DataEncryptHandler.class)
@Data
@TableName(autoResultMap = true)
//fixme 这个用于解密的时候,不加不走自动解密
public class AssetInfo extends Model<AssetInfo> implements Serializable {
@TableId(value = "asset_id",type = IdType.AUTO)
private Integer assetId;
/**
* 资产名称
*/
@TableField(typeHandler = DataEncryptHandler.class)
private String assetName;
}
方法的使用
saveOrUpdate方法
执行逻辑:先执行update方法,根据返回值判断是否需要进行insert操作
last ,getOne
1.无视优化规则直接拼接到 sql 的最后
2.getOne方法查询出多条数据会报错,可以后面拼接个limit 1
blacklistService.getOne(Wrappers.lambdaQuery(Blacklist.class).eq(Blacklist::getStatus, 1).last("limit 1"));
注意事项:
只能调用一次,多次调用以最后一次为准,有sql注入的风险,请谨慎使用
in insql
ArrayList<Long> ids = new ArrayList<Long>() {{
add(1L);
add(2L);
}};
blacklistService.list(Wrappers.<Blacklist>lambdaQuery().in(Blacklist::getId, ids));
blacklistService.list(Wrappers.<Blacklist>lambdaQuery().inSql(Blacklist::getId, "select id from user"));
问题
配置了打印日志仍不打印?
#mybatis-plus:
# configuration:
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 注释掉上面代码
logging:
level:
com:
xx:
xxx:
mapper: debug #这里一直到mapper所在的目录就可以了
update方法不自动填充createTime?
通过update( entity , wrapper )进行操作
而不是update(null,Wrappers.lamadaUpdate().set().eq());