Details
Description
Currently, when you use an enum type as a field in a Grails domain class, it is persisted using its constant name using the varchar(255) type. When you try to customise it using a mapping block with the "sqlType", "type" or "length" parameters, these appear to all be ignored.
For example, given the following enum type:
{{
enum Priority
We can see that the constant in the enum with the longest name is 'MEDIUM' with 6 characters. Let's imagine that we want to use a varchar(6) type rather than varchar(255) because we don't imagine that we'll ever need more than 6 characters for this enum. Therefore we define our domain class as follows:
{{
class Issue {
Priority priority
static mapping =
{ priority length: 6 }}
}}
After doing this, the column in the database is still a varchar(255). Say we then decide to put the SQL type in directly:
{{
static mapping =
}}
But this also doesn't work. It turns out that the 'type' parameter also doesn't have any effect in this situation.
Because of this, not-so-neat work-arounds have to be used, such as declaring the enum types as transients and then creating getter/setter methods for a "mapping" property in the domain class to be persisted instead. An example is as follows:
{{
class Issue {
Priority priority
/**
- Gets the priority name. This is needed to customise the way priority is
- mapped to the database.
* - @return The enum constant name of priority.
*/
String getPriorityName() { priority?.name() }
/**
- The setter, although not really needed, is required because Hibernate
- will otherwise complain that the "priorityName" property doesn't have a
- setter.
* - @param priorityName The enum constant name of the Priority instance to
- set priority to.
*/
void setPriorityName(final String priorityName) { priority = Priority[priorityName] }
static mapping =
{ priorityName column: 'priority', length: 6 } //We'll make 'priority' a transient property to avoid duplication.
static transients = ['priority']
}
}}
This realistic (including appropriate comments and neat spacing) work-around clearly bloats the code quite a lot for a simple customisation of database mapping.
When the 'enumType' mapping parameter is set to 'ordinal' rather than the default of 'string', its likely that the 'precision' and 'scale' mapping parameters also don't have any effect. It's possible that other relevant mapping parameters also don't work for enum types.
Can this behaviour be changed so that enum types' mapping can be customised using the mapping parameters just as with the other types?
Excuse the poor formatting. I tried to use the monospace tags '' and '', but they don't appear to work. I can see now that I should have used the code tag hidden in the 'advanced formatting' section of the formatting help.