Michael
Michael

Reputation: 33317

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?

Upvotes: 0

Views: 544

Answers (1)

micha
micha

Reputation: 49612

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().

Upvotes: 1

Related Questions