grails中的枚举 - 将枚举值保存到域类中

时间:2016-02-06 20:43:37

标签: grails enums gorm

我在/src/groovy/下创建了枚举类UserType:

public enum UserType {
    USER(1),
    DEVSADMIN(2),
    RESTAURANTADMIN(3)
}

我的域类"用户"就像:

class User {
    String  firstName
    String  lastName
    String  emailAddress
    String  contactNumber
    String  password
    String  image
    Date    dateOfBirth

    UserType userType

仍然是我的域类,其字符串类型的user_type字段不是枚举。我想知道,如何为域类USER保存user_type为枚举的数据?

寻找简短的例子,它将包含enum groovy类,域类,控制器和服务。

1 个答案:

答案 0 :(得分:3)

我找到了解决问题的方法: 我创建了一个枚举类" UserType"在路径:src / groovy /

枚举类用户类型如下所示:

public enum UserType {
USER('user'),
DEVSADMIN('devsAdmin'),
RESTAURANTADMIN('restaurantAdmin')
String id

UserType(String id){
    this.id = id
 }
}

域类"用户" ,其中我使用上述枚举类:

class User {
String  firstName
String  lastName
String  emailAddress
String  contactNumber
String  password
String  image
Date    dateOfBirth

UserType userType
static constraints = {
    userType blank : false
  }
 }

控制器中的枚举处理:

class AuthenticationController {

def authenticationService

def userRegistration(){
    Date date = Date.parse("yyyy-MM-dd","1991-01-08")
    authenticationService.userSignUp(   "Abhinandan", "Satpute", abhinandan.satpute@gmail.com", "8796105046", "123", "abc_image",
            date, UserType.RESTAURANTADMIN)
 }
}

使用服务保留枚举值:

class AuthenticationService {

def userSignUp(String firstName, String lastName, String emailAddress, String contactNumber, String password, String image,
               Date dateOfBirth, Enum userType){

    User user   =   new User("firstName" : firstName, "lastName" : lastName, "emailAddress" : emailAddress, "contactNumber" :contactNumber,
            "password" : password, "image" : image, "dateOfBirth" : dateOfBirth, "userType" : userType)
    user.save(flush: true)
 }
}

最后,表格#34; User"好像 : 在此表中" user_type"是在域类中存储为VARCHAR的枚举字段。 schema of table "User" looks like 将记录插入用户表后: after inserting record