tk.mybatis中方法使用注意事项
Example example = new Example(Receiver.class);example.createCriteria().andEqualTo(Receiver.CODE, station.getCode());int count = receiverMapper.selectCountByExample(example);这几行代码有没有问题,实际上达不到我们业务要求的效果,
·
Example example = new Example(Receiver.class);
example.createCriteria().andEqualTo(Receiver.CODE, station.getCode());
int count = receiverMapper.selectCountByExample(example);
这几行代码有没有问题,
实际上达不到我们业务要求的效果,当station.getCode()为空的时候,我们想当然的以为就是查询为空时的条数,但实际并不是。。。
查看andEqualTo的源码
public Example.Criteria andEqualTo(String property, Object value) {
this.addCriterion(this.column(property) + " =", value, this.property(property));
return (Example.Criteria)this;
}
继续查看addCriterion方法
1 protected void addCriterion(String condition, Object value, String property) {
2 if (value == null) {
3 if (this.notNull) {
4 throw new MapperException("Value for " + property + " cannot be null");
5 }
6 } else if (property != null) {
7 this.criteria.add(new Example.Criterion(condition, value));
8 }
9 }
这里面可以看到,如果value为空会走下面,但是下面又多出一个this.notNull,看一下这个表示什么意思
protected abstract static class GeneratedCriteria {
protected List<Example.Criterion> criteria;
protected boolean exists;
protected boolean notNull;//默认值就是false
protected String andOr;
protected Map<String, EntityColumn> propertyMap;
}
这下知道了,第2行到第6行什么都没做,条件没有加上去,最终的效果就是查询了数据库中所有的记录,所以在使用这个方法时需要判断非空。

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)