mybatis-plus操作注意点



一、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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值