MyBatis - MyBatis Generator 生成的example 如何使用 and or 简单混合查询
简单介绍:
Criteria,包含一个Cretiron的集合,每一个Criteria对象内包含的Cretiron之间是由AND连接的,是逻辑与的关系。
oredCriteria,Example内有一个成员叫oredCriteria,是Criteria的集合,就想其名字所预示的一样,这个集合中的Criteria是由OR连接的,是逻辑或关系。oredCriteria就是ORed Criteria。
or()方法,会产生一个新的Criteria对象,添加到oredCriteria中,并返回这个Criteria对象,从而可以链式表达,为其添加Criterion。
能用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 = ? )
作者:无敌的攻城狮
链接:https://www.jianshu.com/p/41ff4cd1649c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。