(快速參考)

column

目的

自訂欄位定義

範例

static mapping = {
        currency column: "currency", sqlType: "char", length: 3
    }

說明

用法:property_name(map)

引數

  • column - 欄位名稱(字串)

  • sqlType(選用) - 基礎 SQL 類型

  • enumType(選用) - 類型安全列舉屬性的列舉類型。可能是 ordinalstringidentity

  • index(選用) - 索引名稱

  • unique(選用) - 是否為唯一

  • length(選用) - 欄位長度

  • precision(選用) - 欄位精度

  • scale(選用) - 欄位比例

  • comment(選用) - 欄位註解(用於建立資料表 DDL)

  • defaultValue(選用) - 資料庫預設值

預設情況下,GORM 使用屬性名稱和類型來決定如何在資料庫中對應屬性。例如,String 屬性通常對應為 varchar(255) 欄位。您可以使用欄位設定引數自訂這些設定

static mapping = {
    currency column: "currency", sqlType: "char", length: 3
}

如果您使用需要多個欄位定義的 Hibernate 類型,可以使用 column 方法定義每個欄位

static mapping = {
    amount type: MonetaryUserType, {
        column name: "value"
        column name: "currency", sqlType: "char", length: 3
    }
}

請注意,如果您有靜態方法與您嘗試設定的屬性名稱相同,或者您使用與 GORM 靜態方法之一相同的屬性名稱,這可能會導致衝突。為避免這種情況,請使用 delegate 屬性設定對應設定的範圍

static mapping = {
    delegate.currency column: "currency", sqlType: "char", length: 3
}

對應 Enum

以下範例說明對應 enum 的不同選項。

給定以下程式碼

package demo

import groovy.transform.CompileStatic

@CompileStatic
class BootStrap {

    def init = { servletContext ->
        Book.saveAll(
            new Book(name: 'Grails 3 - Step by Step',
                     status: Status.NOT_SET),
            new Book(name: 'Grails 3 - A practical guide to application development',
                     status: Status.BORROWED),
            new Book(name: 'Falando de Grails',
                     status: Status.SOLD),
        )
    }
    def destroy = { }
}
package demo

import groovy.transform.CompileStatic

@CompileStatic
enum Status {
    NOT_SET(-1),
    BORROWED(0),
    SOLD(1),

    final int id
    private Status(int id) { this.id = id }
}

對於 enumType ordinal

package demo

class Book {
    String name
    Status status

    static mapping = {
        status enumType: 'ordinal'
    }
}

enum 將在資料庫中對應為

ID

VERSION

NAME

STATUS

1

0

Grails 3 - 分步說明

0

2

0

Grails 3 - 應用程式開發實務指南

1

3

0

談談 Grails

2

對於 enumType identity

package demo

class Book {
    String name
    Status status

    static mapping = {
        status enumType: 'identity'
    }
}

enum 將在資料庫中對應為

ID

VERSION

NAME

STATUS

1

0

Grails 3 - 分步說明

-1

2

0

Grails 3 - 應用程式開發實務指南

0

3

0

談談 Grails

1

對於 enumType string

package demo

class Book {
    String name
    Status status

    static mapping = {
        status enumType: 'string'
    }
}

enum 將在資料庫中對應為

ID

VERSION

NAME

STATUS

1

0

Grails 3 - 分步說明

NOT_SET

2

0

Grails 3 - 應用程式開發實務指南

BORROWED

3

0

談談 Grails

SOLD