0

I'm trying to get my head around GORM and relational mapping. The relationships are working fine but there is one problem. I can't seem too ensure that every MailAddress added to MailingList has a unique address. What would be the must efficient way to do this?

Note: There is no unique constraint on MailAddress.address. Identical addresses can exist in the same table.

class MailAddress {

    String name
    String email

    static belongsTo = MailingList

    static constraints = {
        name blank:true
        email email:true, blank:false
    }
}

class MailingList {

    String name

    static hasMany = [addresses:MailAddress]

    static mapping = {
        addresses cascade: 'all-delete-orphan'
    }

    static constraints = {
        name blank:false
    }
}
Bart
  • 17,070
  • 5
  • 61
  • 80

2 Answers2

1

As mentioned in the comments by @ibaralf the answer is a custom validator. The MailingList class needed to validate if all addresses (MailAddress) have a unique e-mailaddress.

I added this constraint to the MailingList class and it worked.

static constraints = {
    name blank:false

    addresses(validator: {

        if (!it) {
            // validates to TRUE if the collection is empty
            // prevents NULL exception
            return true
        }

        // Grab a collection with all e-mailaddresses in the list
        def addressCollection = it*.email
        // Compare to a collection with only unique addresses
        return addressCollection == addressCollection.unique()
    })
}

More info can be found here http://grails.org/doc/2.2.0/ref/Constraints/validator.html

Bart
  • 17,070
  • 5
  • 61
  • 80
0

There is a unique constraint you can add:

static constraints = {
    name blank:true
    email email:true, blank:false, unique: true
}

=> put the unique constraint on the email variable (unique: true). This would prevent identical email addresses to be saved in the table.

ibaralf
  • 12,218
  • 5
  • 47
  • 69
  • That's the problem. The current table allows duplicates which I can't change at the moment. I only want to achieve uniqueness between the addresses in the mailinglist – Bart Mar 12 '13 at 21:33
  • 1
    If I understood you correctly, you want uniqueness between the hasMany association. If that is the case you can look at this answer http://stackoverflow.com/questions/4041939/how-to-set-uniqueness-at-db-level-for-a-one-to-many-association – ibaralf Mar 12 '13 at 21:47
  • Thanks for mentioning that post!! I read it some days ago, but it gave me a headache because the example provided didn't work. So I went back to the docs and figured it out. Thanks for the help. – Bart Mar 13 '13 at 06:26