Grails: map mysql field of type enum to domain cla

2020-07-17 05:20发布

问题:

How can I map a mysql field of type enum to a grails domain class?

I'm using an existing (legacy) mySQL database with grails v.2.0.3. I'm getting an error for Wrong column type:

failed; nested exception is org.hibernate.HibernateException: Wrong column type in
facilities.ost_fac_syslog for column log_type. Found: enum, expected: varchar(255)

The SQL field is defined as:

mysql> describe ost_fac_syslog;
+------------+---------------------------------+------+-----+--------------------
| Field      | Type                            | Null | Key | Default    
+------------+---------------------------------+------+-----+----------------------+
| log_id     | int(11) unsigned                | NO   | PRI | NULL    auto_increment |
| log_type   | enum('Debug','Warning','Error') | NO   | MUL | NULL    |                |

My domain class is:

class OstFacSyslog {
    static mapping = {
       table 'ost_fac_syslog'
       version false
       id column: 'log_id', name:'logId'
       logType column: 'log_type', type: 'enum', name: 'logType'
    }

    Integer logId
    LogType logType

    enum LogType {
        Debug('Debug'), Warning('Warning'), Error('Error')
            private final String toString
        LogType(String toString) {this.toString = toString}
        String getName() {name()}
        String toString() {toString}
    }
}

Thanks, I appreciate any help.

回答1:

You need to specify the column's sqlType instead of the (Java) type. Change your mapping from:

static mapping = {
    ...
    logType column: 'log_type', type: 'enum', name: 'logType'
}

To:

static mapping = {
    ...
    logType column: 'log_type', sqlType: 'enum', name: 'logType'
}