文章目录
一、mybatis-plus的配置
1、驼峰(属性)和下划线(字段)的映射关系
mybatis中默认是关闭的。
mp中 默认是开启的 ,不需要额外配置。
若要关闭,配置为:
#关闭自动驼峰映射,该参数不能和mybatis-plus.config-location同时存在
mybatis-plus.configuration.map-underscore-to-camel-case=false
2、mybatis-plus分页查询配置
若想进行分页查询,需要 配置 mp的分页插件Bean到IOC容器中:
@Configuration
public class MPPageConfig {
/**
* 分页插件Bean
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}
3、属性在表中不存在 @TableField(exist = false)
@TableField(exist = false) //属性在表中不存在
private String email;
4、有些大字段 不想被sql查询出来
@TableField(select = false) //字段不想被sql查询出来
private Integer age;
二、逻辑查询条件之——or
若你想实现这样的sql效果,where (条件1 and 条件2) or (条件3 and 条件4);
SELECT
*
FROM
tb_user
WHERE
id = 4
OR (
`name` LIKE '%liang%'
AND age > 22
);
对应mp的API为:
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",4).or(i -> i.like("name","liang").gt("age",22));
List<User> userList = userMapper.selectList(queryWrapper);
三、自动填充数据的功能
插入记录时,自动填充数据。
更新记录时,自动更新数据。
可以全局来处理记录的 create_time、update_time值。
步骤:
- 实体类中添加属性 和 注解
/**
* 插入数据时 自动回填数据
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;
/**
* 更新数据时 自动回填数据
*/
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
- 数据库中 添加字段
- 编写自动填充的配置类
/**
* 定义插入/更新记录时,自动填充 哪个字段的值
*
* @author liangqi
* @date 2021/4/18 16:05
*/
@Component
public class MyMetaObjectHander implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
Object createTime = getFieldValByName("createTime", metaObject);
//字段为null,进行赋值
if(Objects.isNull(createTime)){
setFieldValByName("createTime", new Date(),metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
setFieldValByName("updateTime", new Date(),metaObject);
}
}