Explanation of the difference between mybatis createcriteria and or

  • 2021-11-01 03:35:08
  • OfStack

Differences between createcriteria and or

In the example generated by the mybatis generator plug-in, there are createcriteria and or methods. What is the difference between them?

Through the source code, you can clearly see the difference

createcriteria, if there is no rule, it is added to the existing rule, but if there is a rule, it is no longer added to the existing rule, only the created rule is returned


public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
 }

or, the rule created, added to the rule set, and is the relationship of or


public Criteria or() {
    Criteria criteria = createCriteriaInternal();
    oredCriteria.add(criteria);
    return criteria;
}

and and or of Example in mybatis

Can use Example code to solve, I will not write an SQL in the project. I want to make the code as elegant and readable as possible, so here is a record of the use of and and or of Example in MyBatis, mainly in the following two scenarios:

where (Condition 1 and Condition 2) or (Condition 3 and Condition 4) where (Condition 1 and Condition 2) and (Condition 3 or Condition 4)

where (Condition 1 and Condition 2) or (Condition 3 and Condition 4)


// Condition 1 and  Condition 2
example.createCriteria()
        .andEqualTo("isDeleted",IsDeleted.NOT_DELETED)
        .andEqualTo("name", projectCatalogEntity.getName());
//or ( Condition 3 and  Condition 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 (Condition 1 and Condition 2) and (Condition 3 or Condition 4)


// Condition 1 and  Condition 2
example.createCriteria()
        .andEqualTo("isDeleted",IsDeleted.NOT_DELETED))
        .andEqualTo("parentId", projectCatalogEntity.getParentId());
//and ( Condition 3 or  Condition 4)
example.and(example.createCriteria()
        .andEqualTo("name", projectCatalogEntity.getName())
        .orEqualTo("code", projectCatalogEntity.getCode()));

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


Related articles: