项目开发中用到mybatis 的多种条件查询,忽然注意到,example.createCriteria() 并不能清除上一次的条件。
例如:
int score = 10;
UserExample example = new UserExample();
example.createCriteria().andMubhScoreIsNotNull();
// 下面example的条件为MubhScoreIsNotNull
int userCount = userService.countByExample(example);
example.createCriteria().andMubhScoreLessThan(score);
//下面example的条件也为MubhScoreIsNotNull,而不是 MubhScoreLessThan(score)
int userScoreCount = mpUserBookHistoryService.countByExample(example);
出现上面的问题是为什么呢? 分析源码:
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
通过上面的源码发现,只有当 oredCriteria.size() == 0 时,条件才能被插入到oredCriteria中。所以怎么解决呢
1. 通过Example中的clear() ,来清除oredCriteria, 源码中如下:
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
所以清除代码可以这样写:
int score = 10;
UserExample example = new UserExample();
example.createCriteria().andMubhScoreIsNotNull();
// 下面example的条件为MubhScoreIsNotNull
int userCount = userService.countByExample(example);
//清除oredCriteriat
example.clear();
example.createCriteria().andMubhScoreLessThan(score);
//下面example的条件也为MubhScoreIsNotNull,而不是 MubhScoreLessThan(score)
int userScoreCount = mpUserBookHistoryService.countByExample(example);
2. 重新new Example
int score = 10;
UserExample example = new UserExample();
example.createCriteria().andMubhScoreIsNotNull();
// 下面example的条件为MubhScoreIsNotNull
int userCount = userService.countByExample(example);
example = new UserExample();
example.createCriteria().andMubhScoreLessThan(score);
//下面example的条件是 MubhScoreLessThan(score)
int userScoreCount = mpUserBookHistoryService.countByExample(example);
{{ cmt.username }}
{{ cmt.content }}
{{ cmt.commentDate | formatDate('YYYY.MM.DD hh:mm') }}