Question

What is the best way to trim field value in domain?

My suggestion is to use beforeSave(), but would work something like this?

class Book {

  String name = name?.trim()

}
Was it helpful?

Solution

You have a couple options depending on what behavior you want.

  1. A custom setter, which will trim the value every time you set it

    class Book {
        String name
    
        void setName(String name) {
            this.name = name?.trim()
        }
    }
    
  2. A custom getter, which will give you a trimmed value but not store it in the database

    class Book {
        String name
    
        String getName() {
            this.@name?.trim()
        }
    }
    
  3. A hibernate event, like beforeSave() as you mentioned, which will only trim it before the object is persisted.

OTHER TIPS

Well, you can enable automatic trimming of string in Grails (version 2.3+) by setting below property in Config.groovy file:

grails.databinding.trimStrings = true

This will automatic trim the string before save or update.

I have have noticed that Grails automatically does a .trim() on fields before persisting them. For example:

null
""
"      "

All gets stored as null in Grails 2.3.7 for a nullable string. In addition:

"      foobar     "

gets stored as "foobar"

These results are using the default h2 database. So you might let Grails do the heavy lifting in this case.

Here is my hack for quickly trimming all fields in a domain object. I often receive JSON data that is not formatted in a way that would allow me to use data-binding techniques. This method can be called after updating or assigning all values in the domain instance.

class Book {

  def trimFields() {
        this.properties = this.properties
    }

}

Requires this configuration which is set by default in Grails

grails.databinding.trimStrings = true

I know this is overkill but it's quick and easy to add to a domain class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top