Grails: Duplicates & unique constraint validation

Posted by rukoche on Stack Overflow See other posts from Stack Overflow or by rukoche
Published on 2010-05-23T23:27:56Z Indexed on 2010/05/23 23:30 UTC
Read the original article Hit count: 188

Filed under:
|
|

OK here is stripped down version of what I have in my app

Artist domain:

class Artist {

    String name
    Date lastMined
    def artistService

    static transients = ['artistService']
    static hasMany = [events: Event]

    static constraints = {
        name(unique: true)
        lastMined(nullable: true)
    }

    def mine() {
        artistService.mine(this)
    }
}

Event domain:

class Event {

    String name
    String details
    String country
    String town
    String place
    String url
    String date

    static belongsTo = [Artist]
    static hasMany = [artists: Artist]

    static constraints = {
        name(unique: true)
        url(unique: true)
    }
}

ArtistService:

class ArtistService {

    def results = [
        [
            name:"name",
            details:"details",
            country:"country",
            town:"town",
            place:"place",
            url:"url",
            date:"date"
        ]
    ]

    def mine(Artist artist) {
        results << results[0] // now we have a duplicate
        results.each {
            def event = new Event(it)
            if (event.validate()) {
                if (artist.events.find{ it.name == event.name }) {
                    log.info "grrr! valid duplicate name: ${event.name}"
                }
                artist.addToEvents(event)
            }
        }

        artist.lastMined = new Date()
        if (artist.events) {
            artist.save(flush: true)
        }
    }
}

In theory event.validate() should return false and event will not be added to artist, but it doesn't.. which results in DB exception on artist.save()

Although I noticed that if duplicate event is persisted first everything works as intended. Is it bug or feature? :P

© Stack Overflow or respective owner

Related posts about validation

Related posts about grails