1. 程式人生 > >mybatis Example Criteria like 模糊查詢

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
  • 複雜查詢
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());