mybatis createcriteria和or的区别说明

时间:2021-09-22 15:20:05

createcriteria和or的区别

mybatis generator插件生成的example中,有createcriteria和or方法,他们有什么区别呢?

通过源码,能很清楚的看出差别

createcriteria,当没有规则时,则加入到现有规则,但有规则时,不再加入到现有规则,只是返回创建的规则

?
1
2
3
4
5
6
7
public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
 }

or,创建的规则,加入到规则集中,并且是or的关系

?
1
2
3
4
5
public Criteria or() {
    Criteria criteria = createCriteriaInternal();
    oredCriteria.add(criteria);
    return criteria;
}

mybatis中Example的and和or

能用Example代码解决的,我都不会去写个SQL放在项目里。我希望让代码尽量优雅、易读,所以这里记录一下关于MyBatis中Example的and和or的使用,主要是如下两种场景:

  • where (条件1 and 条件2) or (条件3 and 条件4)
  • where (条件1 and 条件2) and (条件3 or 条件4)

where (条件1 and 条件2) or (条件3 and 条件4)

?
1
2
3
4
5
6
7
8
//条件1 and 条件2
example.createCriteria()
        .andEqualTo("isDeleted",IsDeleted.NOT_DELETED)
        .andEqualTo("name", projectCatalogEntity.getName());
//or (条件3 and 条件4)
example.or(example.createCriteria()
        .andEqualTo("isDeleted",IsDeleted.NOT_DELETED)
        .andEqualTo("code", projectCatalogEntity.getCode()));

WHERE ( is_deleted = ? and name = ? ) or ( is_deleted = ? and code = ? )

where (条件1 and 条件2) and (条件3 or 条件4)

?
1
2
3
4
5
6
7
8
//条件1 and 条件2
example.createCriteria()
        .andEqualTo("isDeleted",IsDeleted.NOT_DELETED))
        .andEqualTo("parentId", projectCatalogEntity.getParentId());
//and (条件3 or 条件4)
example.and(example.createCriteria()
        .andEqualTo("name", projectCatalogEntity.getName())
        .orEqualTo("code", projectCatalogEntity.getCode()));

WHERE ( is_deleted = ? and parent_id = ? ) and ( name = ? or code = ? )

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/wangjun5159/article/details/53325540