關於通用Mapper new Example使用記錄


MapperExample使

  • 需要集成 mybatis 的 generator 插件,方便自動生成 實體類和 mapper 類,還可以生成xml,不過一般我們都不用 xml
  • baseMapper 需要繼承 ExampleMapper 不過只需要繼承 Mapper 就可以了,因為 Mapper 已經繼承了 ExampleMapper

Example 的用法

首先需要說明一點 ,和 Example 使用相同的還有 Condition 類 該類繼承自 Example,使用方法和 Example 完全一樣,只是為了避免語義有歧義重命名的一個類,這里我們都用 Example 來說明

  • 創建 Example :
1
Example example = new Example(XXX.class);

其中構造方法為生成的 model 實體類,還有 2 個構造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

/**
* 帶exists參數的構造方法,默認notNull為false,允許為空
*
* @param entityClass
* @param exists - true時,如果字段不存在就拋出異常,false時,如果不存在就不使用該字段的條件
*/
public Example(Class<?> entityClass, boolean exists) {
...
}

/**
* 帶exists參數的構造方法
*
* @param entityClass
* @param exists - true時,如果字段不存在就拋出異常,false時,如果不存在就不使用該字段的條件
* @param notNull - true時,如果值為空,就會拋出異常,false時,如果為空就不使用該字段的條件
*/
public Example(Class<?> entityClass, boolean exists, boolean notNull) {
...
}

然后可以對 example 的實體類的單表進行查詢了

1
2
3
4
Example example = new Example(XXX.class);
example.createCriteria().andGreaterThan("id", 100).andLessThan("id",151);
example.or().andLessThan("id", 41);
List<XXX> list = mapper.selectByExample(example);

以上查詢的條件是,查詢 id 大於 100 並且小於 151 或者 id 小於 41 的記錄

還可以寫成 sql 的方式:

1
2
3
4
5
Example example = new Example(XXX.class);
example.createCriteria().andCondition("id > 100 and id <151 or id < 41");

// andCondition() 方法可以疊加使用,像這樣
example.createCriteria().andCondition("id > 100 and id <151").orCondition("id <41");

andCondition() 有2中使用方法:
andCondition(String condition) : 手寫條件,例如 “length(name)<5”
andCondition(String condition, Object value) : 手寫左邊條件,右邊用value值,例如 “length(name)=” “5”
orCondition() 也是類似的

example 里有很多 mysql 常用的方法,使用方法和 elasticsearch 的 java api 很類似,這里列舉幾個

  • Set<String> selectColumns : 查詢的字段
  • Set<String> excludeColumns : 排除的查詢字段
  • Map<String, EntityColumn> propertyMap : 屬性和列對應
  • andAllEqualTo : 將此對象的所有字段參數作為相等查詢條件,如果字段為 null,則為 is null
  • andGreaterThan : and 條件 大於
  • andBetween : and 條件 between
  • andEqualTo : 將此對象的不為空的字段參數作為相等查詢條件 還有一種有 value 參數的是 = 條件
  • andGreaterThanOrEqualTo : and 條件 》=

還有一些一看就知道意思的

  • andIn
  • andIsNotNull
  • andIsNull
  • andLessThan
  • andLessThanOrEqualTo
  • andNotLike

上面是以 and 條件舉例 ,or的條件也是一樣的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM