關於通用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 |
|
然后可以對 example 的實體類的單表進行查詢了
1 |
Example example = new Example(XXX.class); |
以上查詢的條件是,查詢 id 大於 100 並且小於 151 或者 id 小於 41 的記錄
還可以寫成 sql 的方式:
1 |
Example example = new Example(XXX.class); |
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的條件也是一樣的