1

I faced an exception related "Found shared references to a collection" and i could not find out any solution to overcome. The Problem Occurs under below conditions.

Let's assume Table-1 and Table-2 like

Table-1
ID   Code Other Columns
1    A    . . . . . 
2    A    . . . . .
3    B    . . . . .


Table-2
ID   Source Other Columns
1    A    . . . . . 
2    A    . . . . .
3    B    . . . . .

class Table1 {
   @Id
   private Long id;
   @Column(name = "CODE")
   private String code;
   @OneToMany
   @JoinColumn(name = "SOURCE", referencedColumnName = "CODE")
   private List<Table2> table2List = new ArrayList<>();
}

class Table2 {
   @Id
   private Long id;
   @Column(name = "SOURCE")
   private String source;
 }

when I load all data of Table-1, there will be 3 elements as usual. The problem starts here. table2List variable of first and second elements (code is A) are the same PersistentBag, the same instance of collection(it has 2 elements) and Hibernate throws Found shared references to a collection Exception when transaction is committed. The Collections are already created by Hibernate not me. it seems hibernate bug according to me. I do not know why hibernate does not create different collections for different elements instead of setting the same collection into different elements. How can i solve this problem?

Okay Atalay
  • 71
  • 1
  • 9
  • Read this answer for insight: https://stackoverflow.com/questions/1692871/found-shared-references-to-a-collection-org-hibernate-hibernateexception – scrhartley Aug 31 '23 at 13:28
  • it does not match with my problem. Because, in my case i never set any collection/object to entity. just select query I used – Okay Atalay Aug 31 '23 at 13:39
  • In this example, Source is not unique in Table-2. I don't think that when retrieving the Table2 entities Table1 can identify which ones you are referring to. Really you would need to map by id. It's not a foreign key if it's ambiguous. – scrhartley Aug 31 '23 at 14:04
  • Actually, Table1->element1 and element2 will have the same table2List. Hibernate sets the same collection because, it detects the required FK='A' is already exist in session's internal Map. I what Hibernate not to use same collection – Okay Atalay Aug 31 '23 at 14:09

1 Answers1

0

I found a workaround. just added @Access(AccessType.PROPERTY) over to table2List and updated the setter method to create a new Arraylist instead. it worked properly.

import javax.persistence.Access;
import javax.persistence.AccessType;

class Table1 {
  @Id
  private Long id;
  @Column(name = "CODE")
  private String code;

  @OneToMany
  @JoinColumn(name = "SOURCE", referencedColumnName = "CODE")
  @Access(AccessType.PROPERTY) // update-1
  private List<Table2> table2List = new ArrayList<>();

  // update-2
  public void setTable2List(List<Table2> table2List) {
     this.table2List = new ArrayList<>(table2List);
  }  
  

}

Okay Atalay
  • 71
  • 1
  • 9