Search code examples
grailsgrails-ormdatabase-schemagrails-2.0grails-domain-class

How to set unique hasMany relations based class properties?


I have two domain classes:

class Book {
  String name

  static hasMany = [articles: Article]
}   


class Article {
  String name

  static belongsTo = [book: Book]
}   

I want to validate that a book does have only unique articals in terms of the article name property. In other words: there must be no article with the same name in the same book. How can I ensure that?


Solution

  • You can do this with a custom validator on your Book class (see documentation).

    A possible implementation can look like this:

    static constraints = {
        articles validator: { articles, obj -> 
            Set names = new HashSet()
            for (Article article in articles) {
                if (!names.add(article.name)) {
                    return false
                }
            }
            return true
        }
    }
    

    In this example I am using a java.util.Set to check for duplicate names (Set.add() returns false if the same name is added twice).

    You can trigger the validation of an object with myBookInstance.validate().