How can I map the enum type using Grails 3?

706 views
Skip to first unread message

javacha...@gmail.com

unread,
Nov 10, 2016, 10:11:27 PM11/10/16
to Grails Dev Discuss
Hello, I like the features of GORM provided, so I try to use it in my projects.

Here's my environment setting:

Grails Version: 3.1.6
Groovy Version: 2.4.6
JVM Version: 1.8.0_51

the hibernate is using the default setting, which is:
compile "org.hibernate:hibernate-core:5.1.1.Final"
compile "org.hibernate:hibernate-ehcache:5.1.1.Final"

MySQL version is 5.6.17
I'm running this on Windows 10.

I hope the GORM could automatic generate the DB table looks like this:

| Field       | Type                  | Null | Key | Default | Extra         |
| logtype     | enum('DEBUG','INFO')| NO   |     | NULL    |                |

the SQL scheme looks like this:
create table Todo2 (id bigint not null auto_increment, primary key (id), logType enum("DEBUG", "INFO")) ENGINE=InnoDB

 
This is my domain class define, it seems the mapping is not correct. I tried to follow this link : http://docs.grails.org/3.1.1/ref/Database%20Mapping/column.html
set the enumType  to string or ordinal , but the result is same, the mapped table is not correct.

Anyone can help me?

class Template {

    enum LogType {
        DEBUG("DEBUG"), INFO("INFO")
        String name

        LogType(name) {
            this.name = name
        }
    }

    LogType lt

    static constraints = {
    }

    static mapping = {
        table "Template"
        lt sqlType: "enum", enumType: 'string'
    }
}

Steve Hole

unread,
Nov 24, 2016, 12:09:27 PM11/24/16
to Grails Dev Discuss
Data type mapping is controlled by the hibernate dialect specific to your database. Typically it is mapped to a varchar -- I don't know of any dialects that map to enum because support for that data type has been historically spotty with differences in collation ordering and language support.

We used to try to coerce it the way that you are wanting to, but then we realized that it is more important that we get the form binding and domain object validation right and just let the database store the string serialized form of the enum value. In other words, worry about the values before you store them, but just store them "naked". Of course, if you are accessing the database outside of GORM/Hibernate, you might have a requirement to place more constraints into the data model. 
Reply all
Reply to author
Forward
0 new messages