首先是我一般比较喜欢的写法
一.先建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");
}