0
votes

I have Many-To-Many relationship between RentalUnit and Review(there may be review for guests staying in multiple rental units). There is cascading on Delete from RentalUnit to Review but none cascading from Review to RentalUnit

While working with tests, i found following inconsistency in GORM session

def review2 = new Review(rentalUnits: [rentalUnit], ...., isApproved: false).save(flush: true) review2.addToRentalUnits(rentalUnit2)

The 'rentalUnit2' object will have association to the 'review2' whereas the 'rentalUnit' does not.

enter image description here

How do i ensure consistent session while pass RentalUnit object at initialization or via addTo*?

p.s. Here is complete code class Review { String submittedBy String content String dateReceived boolean isApproved

final static DateFormat DATEFORMAT  = DateFormat.getDateInstance(DateFormat.MEDIUM)

static belongsTo = RentalUnit
static hasMany = [rentalUnits: RentalUnit]

static mapping = {
    rentalUnits cascade: "none"
}

static constraints = {
    submittedBy blank: false, size: 3..50
    content blank: false, size: 5..255
    dateReceived blank: false, size: 11..12, validator: {
        try{
            Date date = DATEFORMAT.parse(it)
            return DATEFORMAT.format(date) == it
        }catch(ParseException exception){
            return false
        }
    }
    rentalUnits nullable: false
}

}

class RentalUnit { String name String nickname Address address static hasMany = [reviews:Review]

static mapping = {
reviews cascade: "all-delete-orphan"
}

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

}

1

1 Answers

1
votes

Your answer is in your question - use addToRentalUnits. It does three things; it initializes the collection to a new empty one if it's null (this will be the case for new non-persistent instances, but not for persistent instances from the database which will always have a non-null (but possibly empty) collection), adds the instance to the collection, and sets the back-reference to the containing instance. Simply setting the collection data just does the first two things.