Search code examples
grailsgrails-orm

Found shared references to a collection exception in grails


I have an exception from the bellow line of code:

  def order = new PostOrder(pOrder: "post", posts: status, children: lookupPerson().children)

the lookupPerson().children gives a set of 2 Child instances with different id's

The full exception is:

  org.hibernate.HibernateException: Found shared references to a collection: com.fyp.timeline.PostOrder.children
at com.fyp.timeline.ProfileController$$ENwi3LDE.updateStatus(ProfileController.groovy:134)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)

I am really stuck on this. Mainly because it did used to work and randomly stopped. I have added a new user to MySql and a new database but that should not effect this one.


Solution

  • You're passing lookupPerson().children to the constructor of the PostOrder - I'm assuming that this is a collection in the Person class mapped with static hasMany = [ ... ]. So Hibernate is telling you what's happening - you're using the same collection twice. It makes sense to me that there should only be one owner of a mapped collection. Keep in mind that these aren't regular ArrayLists or HashSets - they're Hibernate PersistentLists and PersistentSets which implement the correct interfaces but are Hibernate-specific.

    If you want to pass the collection items to the new PostOrder, you can copy them into a new collection, e.g.

    def order = new PostOrder(
        pOrder: "post", posts: status,
        children: [] + lookupPerson().children)
    

    However since this is likely also a mapped collection, you should be using addToChildren, e.g.

    def order = new PostOrder(pOrder: "post", posts: status)
    lookupPerson().children.each { order.addToChildren it }