mybatis createcriteria和or的区别说明
作者:QQ_851228082
这篇文章主要介绍了mybatis createcriteria和or的区别说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
createcriteria和or的区别
mybatis generator插件生成的example中,有createcriteria和or方法,他们有什么区别呢?
通过源码,能很清楚的看出差别
createcriteria,当没有规则时,则加入到现有规则,但有规则时,不再加入到现有规则,只是返回创建的规则
public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; }
or,创建的规则,加入到规则集中,并且是or的关系
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 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 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 = ? )
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。