views:

205

answers:

3

Hi,

In my Grails app I have a domain class that has a property

SearchPrivacy searchPrivacy = SearchPrivacy.PUBLIC

where SearchPrivacy is an enum

enum SearchPrivacy {
    PRIVATE('pr'), PUBLIC('pu');

    final String id

    SearchPrivacy(String id) {
        this.id = id
    }

    static getEnumFromId(String id) {
        values().find {it.id == id}
    }
}

according to the Grails docs, the mapped database column will store either pr or pu - the value of the id property. However, there doesn't seem to be a way to reduce the max length of the DB column. I've tried adding both of the following

static constrtaints = {
    searchPrivacy(size: 2..2, maxSize: 2)
}

But in the generated schema the column is still varchar(255)

Thanks, Don

A: 

I'm not sure how this translates to grails, but in Java it would be done with the @Column(length=2) annotation on the property.

Bozho
By "in Java" do you mean "in Hibernate"?
Don
yes, hibernate is tagged, so I didn't clarify that :)
Bozho
A: 

Your constraints only restrict what you can persist.

If you want to modify the actual SQL type that is persisted you need to declare a static property called 'mapping' in your domain class - much like you are already doing for your constraints. It will look something like this:

static mapping = {
  searchPrivacy type: SearchPrivacy, {
    sqlType: "char(2)"
  }
}

You should always be on the lookout when you see yourself using the sqlType attribute because you could lose the database independence you get from hibernate. (Remember, not all databases support the same types.)

You can also use the 'mapping' property to handle things like custom column names, composite keys and id generation strategies.

I hope this helps!

Brandon
It's untrue that "constraints only restrict what you can persist". If you look at the Grails documentation for the constraints, many of them say "This constraint affects schema generation"
Don
I have seen that in old documentation. I'll remove that.Did the mapping property solve your problem?
Brandon
A: 

May well be a bug. Have you thought about filing a bug report?

John Stoneham