mybatis 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 條件2example.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 條件2example.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 = ? )
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: