Grails: Prevent cascading association between two domain classes with multiple relationships

不问归期 提交于 2019-12-02 07:41:18

This may not be what you are looking for but I would actually model this a little differently - I would have an accepted flag in the Quote domain:

class Job {
    String title
    static hasMany = [quotes: Quote]
}

class Quote {
    static belongsTo = [job: Job]
    BigDecimal quoteAmount
    Boolean accepted
}

Then your persistence could look like this:

jobInstance.addToQuotes(new Quote(quoteAmount: 123.34, accepted: false)) //or true

and no worries regarding your original problem.

You could also add a transient and its getter to the Job class to get the accepted Quote

class Job {
    String title
    static hasMany = [quotes: Quote]

    static transients = ['acceptedQuote']

    Quote getAcceptedQuote() {
        return Quote.findByJobAndAccepted(this, true)
    }

}

Grails/GORM has made the associations simpler by following the methodology of convention over configuration and making things more verbose.

What do you think of the below structure of the domain classes?

class Job {
    String title
    static hasMany = [quotes: Quote]//Job has many Quotes. Note: Accepted Quote is one of them.
}

class Quote {
    BigDecimal quoteAmount
    Boolean isAccepted

    static belongsTo = [job: Job]//Quote always belongs to a Job.
    //When a Job is deleted, quote is also cascade deleted.
}

Now if you create your quote like below then everything should work perfectly:

def job = new Job(title: "Test Job").save()
//Just adding a quote
def quoteInstance = new Quote(quoteAmount: amount)
job.addToQuotes(quoteInstance)
job.save()

//Now accepting that quote
quoteInstance.isAccepted = true
job.save()

Done.

Do we need an acceptedQuote reference in Job? No
How to get to the acceptedQuote?

def acceptedQuote = job.quotes.find{it.isAccepted}

Take a look at hasOne and belongsTo association configuration. Take a look at cascade to learn more about cascade behaviour configuration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!