參考博客:
http://openwares.net/database/mybatis_generator_example.html
一、Example類的作用:一個用於篩選復雜條件的類
二、Example類中查詢方法的介紹
1、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類可以構造你想到的任何篩選條件。
2、Criteria
Criteria包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關系。
3、oredCriteria
Example內有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預示的一樣,這個集合中的Criteria是由OR連接的,是邏輯或關系。oredCriteria就是ORed Criteria。
三、用法舉例:
示例來自官方文檔。
|
TestTableExample example = new TestTableExample();
example.or() 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是這樣的:
|
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條件,這個條件沒有構造方法,直接通過傳遞字符串值指定。