The current enum support in GORM is quite good, but if you use an enum in high-volume domain class (i.e. a lot of rows) than the current approach on mapping the name() value becomes quite inefficient. Switching to the ordinal value can get you in troubles when performing refactorings/migrations. So I'd like to introduce an enhanced solution for the problem:
If the enum has an instance method "getId()" which has a return type that can be mapped as a hibernate basic type (string, int, double, ...) then grails automatically uses a custom usertype (IdentifierEnumType), which performs the mapping using that return value. The id-to-enum value mapping is performed using a bidirectional inmemory map, so it should be quite efficient.
(the feature can be turned of with a configuration option in Config.groovy)
Some example enums that would be mapped with that usertype:
(Groovy version - mapped to the short string value)
public enum Country {
AUSTRIA('at'),
UNITED_STATES('us'),
GERMANY('de');
final String id;
Country(String id) {
this.id = id;
}
}
(Java Version)
public enum Genre {
UNKONWN(-1),
SCIENCE_FICTION(0),
FANTASIY(1),
BIOGRAPHY(2),
NON_FICTION(3);
private final int idVal;
Genre(int id) {
this.idVal = id;
}
public int getId() {
return idVal;
}
}