views:

582

answers:

2

Any ideas on how to persist a collection of enums in Grails?

Groovy enum:

public enum MyEnum {
  AAA('Aaa'),
  BEE('Bee'),
  CEE('Cee')
  String description
  MyEnum(String description) {
    this.description = description
  }
  static belongsTo = [tester:Tester]
}

I want to use this enum in a Grails domain class. The domain class looks like this:

class Tester {
  static hasMany = [myenums: MyEnum]
  static constraints = {
  }
}

In my create.jsp, I want to be able to select multiple MyEnums and have the following line:

<g:select  from="${MyEnum?.values()}" multiple="multiple" value="${testerInstance?.myenums}" name="myenums" ></g:select>`

The problem I'm getting is when I try to create a new Tester, I get a 500 error saying:

Exception Message: java.lang.String cannot be cast to java.lang.Enum
Caused by: java.lang.String cannot be cast to java.lang.Enum
Class: TesterController 
+1  A: 

I haven't done a hasMany to an enum before, but if you give your enums an "id" property, then hibernate will be able to persist it in other relationships (might work with hasMany as well). Here's an example that I've used in the past:

class Qux {
    ...
    BazType baz
    ...
}


enum BazType {
    FOO('foo'),
    BAR('bar')

    final String id

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

Giving your enum an id property might give hibernate enough info to work. See the Grails 1.1 release notes for more info.

Ted Naleid
That removed the exception, but it still isn't persisting the enum value.
BenCourliss
BTW, you have an AWESOME blog Ted! Lots of good info there, so thanks for attempting to answer my question.
BenCourliss
A: 

So the easy fix was to just change the domain class to not use the MyEnum enum type for the myenums variable. Instead I changed it to a String and everything started working.

class Tester {
  static hasMany = [myenums:String]
  static constraints = {
  }
}

Upon further reflection, there really was no need for me to persist the enum type at all. I just wanted the value of the that type saved.

BenCourliss