MyBatis Generator產生的Example類

Example類用於構造複雜的篩選條件。

基本概念

  • Criterion

    Criterion是最基本,最底層的Where條件,用於字段級的篩選,feild用於指代字段名字,列舉如下:

    只有一個條件,不需要其他參考值
    feild IS NOLL
    feild IS NOT NULL

    與一個參考值進行算數運算
    feild > value
    feild >= value
    feild = value
    feild <> value
    feild <= value feild < value 與一個參考值進行模糊查詢,參值中的%,?只能在構造查詢條件時手動指定。 feild LIKE value feild NOT LIKE value 介於兩個參考值之間 feild BETWEEN value AND secondValue 在或不在一個參考值集合中,item來自於value集合 feild IN (item,item,item,...) feild NOT IN (item,item,item,...) MyBatis Generator會爲每個字段產生如上的Criterion,如果表的字段比較多,產生的Example類會十分龐大。理論上通過Example類可以構造你想到的任何篩選條件。

  • Criteria

    Criteria包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關係。

  • oredCriteria

    Example內有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預示的一樣,這個集合中的Criteria是由OR連接的,是邏輯或關係。oredCriteria就是ORed Criteria。

用法

示例來自官方文檔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
TestTableExample example = new TestTableExample();
 
  example.or()
    .andField1EqualTo(5)
    .andField2IsNull();
 
  example.or()
    .andField3NotEqualTo(9)
    .andField4IsNotNull();
 
  List<Integer> field5Values = new ArrayList<Integer>();
  field5Values.add(8);
  field5Values.add(11);
  field5Values.add(14);
  field5Values.add(22);
 
  example.or()
    .andField5In(field5Values);
 
  example.or()
    .andField6Between(3, 7);

or()方法會產生一個新的Criteria對象,添加到oredCriteria中,並返回這個Criteria對象,從而可以鏈式表達,爲其添加Criterion。
產生的動態SQL是這樣的:

1
2
3
4
where (field1 = 5 and field2 is null)
     or (field3 <> 9 and field4 is not null)
     or (field5 in (8, 11, 14, 22))
     or (field6 between 3 and 7)

其他

Example類的distinct字段用於指定DISTINCT查詢。

orderByClause字段用於指定ORDER BY條件,這個條件沒有構造方法,直接通過傳遞字符串值指定。

發佈了36 篇原創文章 · 獲贊 15 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章