能用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 = ? )