(快速參考)

嵌入

目的

支援將網域元件嵌入網域類別中,這也稱為組合

範例

假設有這些網域類別

class Person {

    String name
    Country bornInCountry
    Country livesInCountry

    static embedded = ['bornInCountry', 'livesInCountry']
}

// If you don't want an associated table created for this class, either
// define it in the same file as Person or put Country.groovy under the
// src/main/groovy directory.
class Country {
    String iso3
    String name
}

Grails 會產生一個看起來像這樣的 person 資料庫表格

欄位 類型

NAME

VARCHAR(255)

BORN_IN_COUNTRY_ISO3

VARCHAR(255)

BORN_IN_COUNTRY_NAME

VARCHAR(255)

LIVES_IN_COUNTRY_ISO3

VARCHAR(255)

LIVES_IN_COUNTRY_NAME

VARCHAR(255)

說明

嵌入式元件不會像一般的網域類別關聯那樣將其資料儲存在自己的表格中。資料會包含在擁有者的表格中。因此在上述範例中,Country 欄位會出現在 person 表格中。這表示查詢會更快,因為不需要聯結,但可能會在表格中產生重複資料。

嵌入式元件類別通常會宣告在與擁有者類別相同的原始檔中,或在 src/main/groovy 下的自己的檔案中。可以將元件類別放在 grails-app/domain 下,但如果這樣做,Grails 會自動為其建立一個專屬表格。通常將類別放在 src/main/groovy 下是最好的選擇,因為這樣就可以在多個網域類別中共用元件。

查詢嵌入式屬性與查詢一般關聯沒有不同,因此仍然可以執行

Person.findAllByBornInCountry(brazil)
Person.findAllByLivesInCountry(france)

其中 brazilfranceCountry 的實例。