Change SQL datatype for Grails domain String fields

07 / Jun / 2010 by Uday Pratap Singh

The Grails automatically identifies what should be the datatype of the field in sql table e.g; fields with String datatype are converted to varchar(255), but sometimes we need to store the data more than 255 characters. In such cases earlier I used to alter the table in the database. But now I found the better solution for this problem. Again a simple configuration in the domain class can do the trick for you. In static mapping of domain class you just need to assign the type to that particular field. If you want to store the huge data you can assign “text” to it

class Event {
    String title;
    Date date;
  
    static mapping = {
        title type:"text"
    }
}

If this doesn’t look a right solution to you and you want specific length to the data as we can do in database you can do that here as well

 static mapping = {
        title column: "title", sqlType: "varchar(5000)"
    }

This is really so easy, its just I never looked for the right solution

Hope it helps
Uday Pratap Singh
uday@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. Nathan

    Except just using constraints to let it guess the best data type can give you intelligent things like varchar(1000000) instead of text.

  2. Uday

    oh yes I forgot that simple constraint. Thanks Soren. Actually for specific length we should do it in constraints. The sqlType method would be appropriate for other fields like date. As per my understanding date fields in grails are stored as datetime in sql .

    For date field if we want sql date typle we can do use date sqlType: “date” in static mapping.

    Thanks for reminding me

  3. Søren Berg Glasius

    Why not use a constraint:

    static constraints = {
    title size: 1..5000
    }

    That way Grails automatically figures out that it should use a type of “text” in the database.

    Best regards,
    Søren

Comments are closed.