MyBatis Generator 自動生成的POJO對象的使用(二)


四、Example Class使用說明

  示例類指定如何構建動態where子句。

  表中的每個非BLOB列都可以選擇包含在where子句中。 示例是演示此類用法的最佳方法。

  示例類可用於生成幾乎無限制的where子句。

 

  Example類包含一個名為Criteria的內部靜態類,Criteria類包含了一個條件List,這些條件都會通過“and”運算添加到where子句中。

  Example 類包含一個Criteria對象的List,源自內部類的所有子句都將通過“or”運算連接起來。

  使用不同的Criteria類集允許您生成幾乎無限制類型的where子句。

 

  可以使用Example類中的createCriteria方法或“or”方法創建Criteria對象。

  當使用createCriteria方法創建第一個Criteria對象時,它會自動添加到Criteria對象列表中 - 如果您不需要或其他幾個子句,則可以輕松編寫簡單的where子句。

  使用or方法時,Criteria類將被添加到所有實例的列表中。

  

  重要提示:

  我們建議您僅使用or方法創建Criteria類。 我們相信這種方法可以使代碼更具可讀性。

 

  4.1、簡單查詢

  此示例顯示如何使用生成的示例類生成簡單的WHERE子句:

TestTableExample example = new TestTableExample();

example.createCriteria().andField1EqualTo(5);

  或者,以下語法也奏效:

TestTableExample example = new TestTableExample();

example.or().andField1EqualTo(5);

  在上面的任何一個例子中,動態生成的where子句實際上是:

where field1 = 5

 

  4.2 復雜查詢

  下一個示例演示如何使用生成的示例類生成復雜的WHERE子句(使用JSE 5.0參數化類型)

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)

  返回的records(記錄)將會符合這些條件。

 

  4.3、非同查詢(Distinct Queries)

  您可以通過在任何示例類上調用setDistinct(true)方法來強制查詢為DISTINCT。

 

  4.4、條件類(Criteria Classes)

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

  • IS NULL - meaning the related column must be NULL
  • IS NOT NULL - meaning the related column must not be NULL
  • = (equal) - meaning the related column must be equal to the value passed in on the method call
  • <> (not equal) - meaning the related column must not be equal to the value passed in on the method call
  • > (greater than) - meaning the related column must be greater than the value passed in on the method call
  • >= (greater than or equal) - meaning the related column must be greater than or equal to the value passed in on the method call
  • < (less than) - meaning the related column must be less than the value passed in on the method call
  • <= (less than or equal) - meaning the related column must be less than or equal to the value passed in on the method call
  • LIKE - meaning the related column must be "like" the value passed in on the method call. The code does not add the required '%', you must set that value yourself in the value you pass in on the method call.
  • NOT LIKE - meaning the related column must be "not like" the value passed in on the method call. The code does not add the required '%', you must set that value yourself in the value you pass in on the method call.
  • BETWEEN - meaning the related column must be "between" the two values passed in on the method call.
  • NOT BETWEEN - meaning the related column must be "not between" the two values passed in on the method call.
  • IN - meaning the related column must be one of the list of values passed in on the method call.
  • NOT IN - meaning the related column must not be one of the list of values passed in on the method call.

 

五、擴展Example類

  在某些情況下,可能需要擴展生成的示例類。

  您可能希望添加特定於數據庫的條件(例如Oracle ROWNUM支持),或添加未自動生成的條件(例如不區分大小寫的搜索)。

  在這些情況下,您可以擴展生成的示例類以添加這些附加條件。

 

  5.1、通用原則

  MyBatis Generator(MBG)會為每個表生成一個“示例”類,除非在配置中另有說明。 

  “example”類用於生成在xxxByExample語句中使用的動態where子句。 標准“example”類會包含所有標准SQL謂詞的功能。

  在某些情況下,可能需要為應用程序的特定需求添加其他謂詞。 這可能包括添加對非標准謂詞的支持,或者在where子句中使用特定於數據庫的函數。

 

  生成的“example”類包含一個嵌套的內部類,其中存在謂詞的實際功能。

  這個內部類始終命名為GeneratedCriteria。 MBG還生成一個名為Criteria的內部類,它擴展了GeneratedCriteria,您可以使用它來將自己的函數添加到示例類中。

  Eclipse Java代碼合並不會刪除Criteria類,因此您可以添加它,而不必擔心在重新生成時丟失更改。

  例如,假設有一個名為CUSTOMER的表。 通常,MBG會生成一個名為CustomerExample的類。要向CustomerExample類添加功能,您應該向CustomerExample.Criteria類添加其他方法。

 

  5.2、Extending vs Plugging ln

  如果您頻繁擴展示例類,那么創建一個插件以生成附加功能而不是手動編寫擴展類可能會更方便。

  下面的示例(在“Single Parameter Predicates”標題下)也可以使用插件來完成,如org.mybatis.generator.plugins.CaseInsensitiveLikePlugin類所示。

 

  5.3、添加謂詞(Adding Predicates)

  MBG生成一個動態SQL片段,允許在運行時創建幾乎沒有限制的where子句。為此,生成的SQL片段支持四種廣泛類型的SQL謂詞。對於每種類型的SQL謂詞,GeneratedCriteria內部類中都有一個相應的方法,可用於向動態where子句添加謂詞。

  1、簡單的字符串替換

  當不需要將參數對象中的屬性代入where子句時,將使用此類型的謂詞。示例:

FIRST_NAME is null
LAST_NAME is not null

  此謂詞在GeneratedCriteria類中的方法是:

addCriterion(String anyString)

  其中“anyString”是要代入where子句的字符串。此方法可用於向生成的where子句添加任何類型的測試。

  例如,假設您想使用SOUNDEX函數執行“sounds like”名稱搜索。在MySQL中,謂詞應如下所示:

SOUNDEX(FIRST_NAME) = SOUNDEX('frod')

  這個謂詞太復雜而無法使用任何其他方法,因此必須通過簡單的字符串替換將其插入到where子句中。將以下方法添加到Criteria內部類以實現此功能:

public Criteria andFirstNameSoundsLike(String value) {
  StringBuffer sb = new StringBuffer("SOUNDEX(FIRST_NAME) = SOUNDEX('");
  sb.append(value);
  sb.append("')");

  addCriterion(sb.toString());

  return this;
}

  以下代碼顯示了使用selectByExample方法使用此新功能:

CustomerExample example = new CustomerExample();
Criteria criteria = example.createCriteria();
criteria.andFirstNameSoundsLike("frod");
List results = selectByExample(example);

  此方法可用於將幾乎任何謂詞添加到where子句。但是,如果可能,通常最好使用參數替換,因為存在正確格式化不同數據類型的問題(最明顯的是日期,時間和時間戳)。

  此外,如果您暴露了一個過於通用的方法,則此方法可能會出現SQL注入問題。 如果可能,我們建議使用下面列出的其他方法之一。

 

  2、單參數謂詞(Single Parameter Predicates)

  當參數對象中有一個屬性要代入為where子句時,將使用這種類型的謂詞。

  例如:

FIRST_NAME = ?
LAST_NAME <> ?

  為此謂詞生成的Criteria類方法是:

 addCriterion(String anyString, Object anyObject, String propertyName)

  anyString 是在參數替換之前代入where子句的字符串。

  anyObject 是字符串替換后代入where子句的Object

  propertyName的 是一個字符串,表示與此子句相關的屬性名稱。此字符串僅用於潛在的錯誤消息。

 

  此方法可用於將與單個參數相關的簡單測試添加到生成的where子句中。

  例如,假設您要對某些列執行不區分大小寫的搜索。 在MySQL中,謂詞可能如下所示:

upper(FIRST_NAME) like ?

  此謂詞適合單個參數謂詞的功能 - 其中謂詞是字符串值,后跟單個參數。

  將以下方法添加到ExtendedCriteria以獲得此功能:

public ExtendedCriteria andFirstNameLikeInsensitive(String value) {
  addCriterion("upper(FIRST_NAME) like",
    value.toUpperCase(), "firstName");

  return this;
}

  以下代碼顯示了使用selectByExample方法使用此新功能:

ExtendedExample example = new ExtendedExample();
ExtendedCriteria criteria = (ExtendedCriteria) example.createCriteria();
criteria.andFirstNameLikeInsensitive("fred%");
List results = selectByExample(example);

 

  3、List Predicates

  列表謂詞用於將可變大小的值的列表作為參數添加到where子句。

  例子包括:

FIRST_NAME IN (?, ?, ?)
LAST_NAME NOT IN (?, ?, ?, ?)

  此謂詞的靈活性低於其他謂詞,因為它專門用於“in”和“not in”標准謂詞。

  盡管如此,如果您發現它的一些用途,Criteria類中的相應方法如下:

 addCriterion(String anyString, List listOfObjects, String propertyName)

  anyString是在參數替換之前代入where子句的字符串

  listOfObjects是字符串替換后要替換為where子句的對象列表(在列表之前將附加一個左括號,列表項將以逗號分隔,並且在列表之后將附加一個右括號)。

  propertyName的是一個字符串,表示與此子句相關的屬性名稱。 此字符串僅用於潛在的錯誤消息。

 

  4、Between predicates

  Between predicates用於將兩個參數添加到特定格式的where子句中。

  例子包括:

FIRST_NAME BETWEEN ? AND ?
LAST_NAME NOT BETWEEN ? AND ?

  此謂詞的靈活性低於其他謂詞,因為它專門用於“between”和“not between”標准謂詞。盡管如此,如果您發現它的一些用途,Criteria類中的相應方法如下:

addCriterion(String anyString, Object object1, Object object2, String propertyName)

  anyString是在參數替換之前代入where子句的字符串。

  object1是字符串替換后代入where子句的對象(單詞“and”將在此對象后面附加)。

  object2是要代入單詞“and”之后的where子句的對象。

  propertyName是一個字符串,表示與此子句相關的屬性名稱。 此字符串僅用於潛在的錯誤消息。

 

五、MyBatis Dynamic SQL使用說明

  此頁面簡要介紹了如何使用為MyBatis3DynamicSQL運行時生成的類

  這些類依賴於MyBatis Dynamic SQL庫。有關庫如何工作的完整信息,請參閱該站點。

 

  對於每個內省表,生成器將生成三個對象:

  • 表示表中一行的“record”類。 這與其他運行時相同;
  • 一個“support”類,包括數據庫表的表定義和列定義;
  • 映射器接口,包含其他運行時生成的所有典型方法。

  關於這些生成的對象的說明:

  • 有關生成的對象的重要說明:
  • 沒有生成XML
  • 沒有生成單獨的“Example”類
  • 沒有單獨的“with BLOBs”和“without BLOBs”方法。 如果您的表包含BLOB字段,則它們將包含在所有操作中。
  • 模型類總是在“flat”模型中生成,這意味着沒有單獨的主鍵類或BLOB類
  • 需要Java 8或更高版本
  • 需要MyBatis 3.4.2或更高版本

 

  5.1、support類的格式

  每個表都會創建一個“support”類。

  support類包括表的定義和表中的所有列。 這些項目用作映射器中生成的代碼的輸入 - 通常用於您將編寫的where子句。

  例如,假設數據庫“MYSCHEMA”中有一個表“TABLE_CODE”。 進一步假設該表具有“ID”和“DESCRIPTION”列。 生成的支持類將如下所示:

package example;

import java.sql.JDBCType;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;

public final class TableCodeDynamicSqlSupport {
    public static final TableCode tableCode = new TableCode();
    public static final SqlColumn<Integer> id = tableCode.id;
    public static final SqlColumn<String> description = tableCode.description;

    public static final class TableCode extends SqlTable {
        public final SqlColumn<Integer> id = column("ID", JDBCType.INTEGER);
        public final SqlColumn<String> description = column("DESCRIPTION", JDBCType.VARCHAR);

        public TableCode() {
            super("MYSCHEMA.TABLE_CODE");
        }
    }
}

  在您的代碼中,通常導入此支持類的靜態元素,以便可以直接在您編寫的代碼中使用它們。使用此靜態導入,您可以以直接或合格的方式引用字段 - “id”或“tableCode.id”。

 

  5.2  Mapper類的使用

  以下方法與其他運行時的工作方式相同,我們不會在此處介紹它們:

  • Delete by Primary Key
  • Insert - will insert nulls
  • insert selective - ignores null properties
  • Select by Primary Key
  • Update by Primary Key - will set null values
  • Update by Primary Key Selective - ignores null values

  而"by example"放啊卻很不同,生成器將創建以下“通過示例”方法:

  • Count by example
  • Delete by example
  • Select by example
  • Update by example

  這些方法中的每一個都包括對非常靈活的WHERE子句的支持。每個方法都返回一個構建器對象( a builder object ),該對象要求您可以選擇添加WHERE子句,然后完成構建器並執行該方法。

  如果您不提供WHERE子句,則該語句仍然有效 - 但它將應用於表的所有行。 通過調用構建方法完成所有構建器,最后通過調用execute方法執行語句。

  例如,您可以通過在沒有WHERE子句的情況下調用count by example方法來檢索表中的總行數。 該代碼如下所示:

long totalRows = mapper.countByExample()
          .build()
          .execute();

  您可以通過調用select by example而不使用WHERE子句來檢索表中的所有行:

 List<TableCode> allRecords = mapper.selectByExample()
          .build()
          .execute();

  將WHERE子句添加到這些方法中會更有趣。要添加對WHERE子句的支持,您應該從support類導入靜態元素,如上所示,您還應該導入SqlBuilder支持。然后你可以編碼任意復雜的where子句和“ORDER BY”短語,如下所示:

import static example.TableCodeDynamicSqlSupport.*;  // import the generated "support" items
import static org.mybatis.dynamic.sql.SqlBuilder.*;  // import MyBatis Dynamic SQL where support

public class SomeService {

    public void simpleWhere {
        ...
        // Simple WHERE clause
        List<TableCode> records = mapper.selectByExample()
                .where(id, isEqualTo(3))
                .build()
                .execute();        
        ...
    }

    public void complexWhere1 {
        ...
        // Simple WHERE clause with OR
        List<TableCode> records = mapper.selectByExample()
                .where(id, isEqualTo(3))
                .or(description, isLike("f%"))
                .build()
                .execute();        
        ...
    }

    public void complexWhere2 {
        ...
        // complex WHERE and ORDER BY
        List<TableCode> records = mapper.selectByExample()
                .where(id, isLessThan(10), and(description, isEqualTo("foo")))
                .or(description, isLike("b%"))
                .orderBy(id.descending())
                .build()
                .execute();        
        ...
    }
}

  此運行時中的“by example”方法比其他運行時中的“by example”方法靈活得多。請獲取MyBatis Dynamic SQL的文檔以了解有關可用選項的更多信息。

  

 


免責聲明!

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



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