MyBatis-Plus基础应用和踩坑

首先是我一般比较喜欢的写法

一.先建Mapper层

@Mapper
public interface StudentMapper extends BaseMapper<Student> {

}

二.再建立接口

public interface StudentService extends IService<Student> {


}

三.And实现类

@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper,Student> implements StudentService {
    
}

四.用应用层自带的增删改查的方法

除非涉及到连表查询等复杂查询,用mabits-plus自带的增删改查已经足够用了

比如一个简单List查询

        List<Student> studentList= StudentService
                        .list(Wrappers.<Student>lambdaQuery()
                        .eq(Student::getId, id)
                        .isNull(Student::getUpdateDate));

然后就是踩坑And实践

一.无法使用updateById() 方法更新null值

在我日常开发中,很少会用update()方法去写一些更新操作,更多的是使用updateById()去更新表中的值比较好用,传入一个对应实体类更新数据即可,有次遇到了前端处理后为null的数据发现无法去真正置空,方法如下

if (request.getPrice()==null){
            LambdaUpdateWrapper<Shop> wrapper = new LambdaUpdateWrapper<Shop>();
            wrapper.eq(Shop::getShopId,shopId);
            wrapper.set(Shop::getPrice,null);
            shopDao.update(tableShopInfo,wrapper);
        }
可能上面方法只能说是水多了加面,面多了加水的操作,但是这样的临时对一个字段进行特殊操作比较快捷实现

二.getOne()操作报错

目前手头开发的项目中有很多的getOne()的操作,这更多的要求的数据库字段的唯一性质,如果出现获取两个或者更多了就会报错

userAccountLogService.getOne(Wrappers.<UserAccountLog>lambdaQuery().eq(UserAccountLog::getStatus,1),false);
在后面加一个false参数,就会只拿第一个.但是这种情况适用于报错的影响小于数据错误的情形,如果只取第一个数据导致数据污染也是影响比较大的

三.条件拼接

在项目中可能需要一个关键字搜索匹配可以搜索到很多条内容,关联数个字段

 wrapper.and(a->a.like(StringUtils.isNotEmpty(userAccountLogDto.getKey()),"mobile",userAccountLogDto.getKey())
                    .or(b->b.like(StringUtils.isNotEmpty(userAccountLogDto.getKey()),"user_name",userAccountLogDto.getKey()))
                    .or(c->c.like(StringUtils.isNotEmpty(userAccountLogDto.getKey()), "remark", userAccountLogDto.getKey())));

这种稍微复杂一些,还有一种适合条件不多的情况.or()在中间拼接条件即可

a.eq(MerchantPromoter::getName, request.getName()).or().eq(MerchantPromoter::getTelephone, request.getTelephone())

四.特殊条件getMap

在项目中有时候还会遇到想要取数量的情况

如果不想要在实体类中附属属性或者是没有实体类的形式的话可以使用这种方法

wrapper1.select("sum(amount) as blance");
Map<String, Object> map = userAccountLogService.getMap(wrapper1);
if (CollectionUtil.isNotEmpty(map)&&map.size()>0){
            sum=map.get("blance")==null?new BigDecimal("0.00"):(BigDecimal)map.get("blance");
        }

  • 19
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值