user3256520
user3256520

Reputation: 451

How to make the enum field a tinyint instead of varchar?

I have a domain class defined as

class QuestionSurvey {

    String questionText
    QuestionTypeSurvey questionType

    static hasMany = [options: QuestionOptionSurvey]

    static constraints = {}
}

Now, in the above domain QuestionTypeSurvey is a enum class which I have defined inside src/groovy since I don't want a separate table for this field. The QuestionTypeSurvey is defined as following:

enum QuestionTypeSurvey {

        TEXT_FIELD,
        TEXT_AREA,
        RADIO_BUTTON,
        DROPDOWN_BOX,
        CHECK_BOX
}

Now, when I run the application and look at the table structures I noticed that the questionType field in QuestionSurvey table is not a tiny int which I had expected since it is pointing to an enum but it was VARCHAR. I was puzzled. Is there anyway to make the type a tinyint instead of varchar since that was the whole point of using enum rather than strings? Thanks for the help!

Upvotes: 0

Views: 245

Answers (1)

MattZ
MattZ

Reputation: 266

You can add a mapping configuration in your domain class so the enum is stored as an int instead. I'm not sure how to force that to be a tinyint but at least it's not a varchar.

static mapping = {
    questionType enumType: 'ordinal'
}

Grails doc: http://www.grails.org/doc/latest/ref/Database%20Mapping/column.html

You can also add an id field to the Enum class and define the values being stored if needed. http://blog.tamashumi.com/2013/06/grails-enum-custom-database-value.html

Upvotes: 2

Related Questions