在Grails域类中使用ENUM

Al-*_*unk 7 grails enums grails-orm

Grails上有一些ENUM的例子(这里也是SO),但我无法得到理想的结果.

解决方案包括1)将ENUM放在src/groovy 域类下的单独 类中

class Offer {
    PaymentMethod acceptedPaymentMethod 
    ..
}
Run Code Online (Sandbox Code Playgroud)

src/groovy PaymentMethod

public enum PaymentMethod {
    BYBANKTRANSFERINADVANCE('BANKADVANCE'),
    BYINVOICE('ByInvoice'),
     CASH('Cash'),
    CHECKINADVANCE('CheckInAdvance'),
    PAYPAL('PayPal'),
    String id

    PaymentMethod(String id) {
        this.id = id
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,在发出错误的域类中根本不识别Enum类.看起来这个曾经在版本2之前用于Grails.

我在这里错过了什么吗?如何在Grails的域中使用外部ENUM类?

2)将ENUM放在域类中.

在这种情况下,grails在编译时不会抱怨,但是脚手架不包含ENUM值的任何信息(就像在scaffolding过程中不包含属性acceptedPaymentMethod)示例:

class Offer {
    PaymentMethod acceptedPaymentMethod 
    ..
    enum PaymentMethod {
        BYBANKTRANSFERINADVANCE('BANKADVANCE'),
        BYINVOICE('ByInvoice'),
        CASH('Cash'),
        CHECKINADVANCE('CheckInAdvance'),
        PAYPAL('PayPal'),
        String id

        PaymentMethod(String id) {
            this.id = id
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

检查数据库表的结构,该字段不是ENUM而是简单的VarChar:

| accepted_payment_method        | varchar(255) | YES  |     | NULL    |                |
Run Code Online (Sandbox Code Playgroud)

是否支持Grails Gorm上的ENUM?

小智 4

刚刚尝试使用 Grails 2.3.4,它可以使用src/groovy方法:

src/groovy/PaymentMethod.groovy

public enum PaymentMethod {
    BYBANKTRANSFERINADVANCE('BANKADVANCE'),
    BYINVOICE('ByInvoice'),
     CASH('Cash'),
    CHECKINADVANCE('CheckInAdvance'),
    PAYPAL('PayPal'),
    String id

    PaymentMethod(String id) {
        this.id = id
    }
}
Run Code Online (Sandbox Code Playgroud)

grails-app/domain/CustomDomain.groovy

class CustomDomain {
  PaymentMethod acceptedPaymentMethod
}
Run Code Online (Sandbox Code Playgroud)

然后我运行了grails generate-all CustomDomain,这是_form.gsp它生成的:

<div class="fieldcontain ${hasErrors(bean: customDomain, field: 'acceptedPaymentMethod', 'error')} required">
    <label for="acceptedPaymentMethod">
        <g:message code="customDomain.acceptedPaymentMethod.label" default="Accepted Payment Method" />
        <span class="required-indicator">*</span>
    </label>
    <g:select name="acceptedPaymentMethod" from="${custombinds.PaymentMethod?.values()}" keys="${custombinds.PaymentMethod.values()*.name()}" required="" value="${customDomain?.acceptedPaymentMethod?.name()}"/>
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,在 Grails 2.3.x 中,脚手架功能已转换为插件,因此您需要在您的 中包含以下内容BuildConfig.groovy

compile ":scaffolding:2.0.1"
Run Code Online (Sandbox Code Playgroud)