Skip to content
This repository has been archived by the owner on Jan 19, 2022. It is now read-only.

Commit

Permalink
fix for GRAILS-8815 "Domain hasMany association using a List is addin…
Browse files Browse the repository at this point in the history
…g duplicate items when the parent is saved"
  • Loading branch information
graemerocher committed May 9, 2012
1 parent b2cb2e8 commit 48b9f6d
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -888,16 +888,18 @@ else if (association.doesCascade(CascadeType.PERSIST)) {
Object inverseEntity = entityAccess.getProperty(association.getName());
if (inverseEntity != null) {
EntityAccess inverseAccess = createEntityAccess(association.getAssociatedEntity(), inverseEntity);
Object entity = entityAccess.getEntity();
if (inverse instanceof OneToMany) {
Collection existingValues = (Collection) inverseAccess.getProperty(inverse.getName());
if (existingValues == null) {
existingValues = MappingUtils.createConcreteCollection(inverse.getType());
inverseAccess.setProperty(inverse.getName(), existingValues);
}
existingValues.add(entityAccess.getEntity());
if(!existingValues.contains(entity))
existingValues.add(entity);
}
else if (inverse instanceof ToOne) {
inverseAccess.setProperty(inverse.getName(), entityAccess.getEntity());
inverseAccess.setProperty(inverse.getName(), entity);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package org.grails.datastore.gorm

import spock.lang.Specification
import spock.lang.Issue
import grails.persistence.Entity
import grails.gorm.tests.GormDatastoreSpec

/**
*/
class AutoLinkOneToManyAssociationSpec extends GormDatastoreSpec{

@Issue('GRAILS-8815')
void "Test that associations are linked automatically when saving"() {
given:"A new domain class with a one-to-many association"
def author = new AutoLinkListAuthor(firstName:'foo', lastName: 'bar')
when:"The domain is saved"
author.save()
then:"The association is intially empty"
author.id != null
author.books == null

when:"An associated object is added"
def book1 = new AutoLinkListBook(title: 'grails', price: 43, published: new Date(), author: author)

// add the book to the author to complete the other side
author.addToBooks(book1)
then:"The relationship size is correct"
author.books.size() == 1

when:"The domain is saved"
author.save()
then:"The relationship size is still correct"
author.books.size() == 1
}

@Override
List getDomainClasses() {
[AutoLinkListAuthor,AutoLinkListBook]
}


}

@Entity
class AutoLinkListAuthor {
Long id
String firstName
String lastName

// Hi, see here!
List books

static hasMany = [books: AutoLinkListBook]
}

@Entity
class AutoLinkListBook {
Long id
String title
Date published
BigDecimal price

static belongsTo = [author: AutoLinkListAuthor]
}

0 comments on commit 48b9f6d

Please sign in to comment.