mybatis Example Criteria like 模糊查詢


用Mybatis代碼生成工具會產生很多個XXXExample類,這些類的作用是什么?

查閱了很多資料,在這里總結歸納一下

簡介
XXXExample類用於構造復雜的篩選條件

它包含一個名為Criteria的內部靜態類,它包含將在where子句中一起結合的條件列表。

Criteria類的集合允許您生成幾乎無限類型的where子句。

可以使用createCriteria方法或or方法創建Criteria對象。

當使用createCriteria方法創建第一個Criteria對象時,它會自動添加到Criteria對象列表中 -

如果不需要其他子句,則可以輕松編寫簡單的Where子句。使用or方法時,Criteria類將添加到所有實例的列表中。

官方建議僅使用or方法創建Criteria類。這種方法可以使代碼更具可讀性。

Criteria類
Criteria內部類包括每個字段的andXXX方法,以及每個標准SQL謂詞,包括:

字段方法 含義
IS NULL 表示相關列必須為NULL
IS NOT NULL 表示相關列不能為NULL
=(等於) 表示相關列必須等於方法調用中傳入的值
<>(不等於) 表示相關列不能等於方法調用中傳入的值
>(大於) 表示相關列必須大於方法調用中傳入的值
> =(大於或等於) 表示相關列必須大於或等於方法調用中傳入的值
<(小於) 表示相關列必須小於方法調用中傳入的值
<=(小於或等於) 表示相關列必須小於或等於方法調用中傳入的值
LIKE 意味着相關列必須“類似”方法調用中傳入的值。代碼不會添加所需的’%’,您必須自己在方法調用中傳入的值中設置該值。
NOT LIKE 意味着相關列必須“不喜歡”方法調用中傳入的值。代碼不會添加所需的’%’,您必須自己在方法調用中傳入的值中設置該值。
BETWEEN 意味着相關列必須“在”方法調用中傳入的兩個值之間。
NOT BETWEEN 意味着相關列必須“不在”方法調用中傳入的兩個值之間。
IN 表示相關列必須是方法調用中傳入的值列表之一。
NOT IN 表示相關列不能是方法調用中傳入的值列表之一。
簡單實例
生成簡單的WHERE子句
TestTableExample example = new TestTableExample();

example.createCriteria().andField1EqualTo(5);

或者

TestTableExample example = new TestTableExample();

example.or().andField1EqualTo(5);
實際上動態生成的where子句是這樣

where field1 = 5
1
復雜查詢
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);
實際上動態生成的where子句是這樣

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)

可以通過在任何示例類上調用setDistinct(true)方法來強制查詢為DISTINCT。
模糊查詢實戰
自己根據理解配合PageHelper做了一個簡單的多條件模糊查詢加深理解

具體實現如下,支持多個字段的同時搜索

PageHelper.startPage(pageNum,pageSize);
TbBrandExample example = new TbBrandExample();
TbBrandExample.Criteria criteria = example.createCriteria();
if (tbBrand != null) {
if (tbBrand.getName() != null && tbBrand.getName().length()>0) {
criteria.andNameLike("%"+tbBrand.getName()+"%");
}
if (tbBrand.getFirstChar() != null && tbBrand.getFirstChar().length()>0) {
criteria.andFirstCharLike("%"+tbBrand.getFirstChar()+"%");
}
}
Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(example);
return new PageResult((int) page.getTotal(),page.getResult());


免責聲明!

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



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