Reputation: 12140
I had following entities in my project:
AccountGroup
AccountItem
AccountSegment
With folowing relations:
AccountGroup
has List<AccountItem>
AccountItem
had List<AccountSegment>
and everything worked fine.
When I changed last relation to:
AccountItem
has Set<AccountSegment>
AccountGroup
object read from database looks strange. If given AccountItem
had three AccountSegment
s, then I have three the same AccountItem
s in AccountGroup
.
A shot from debugger can possibly tell it better than I can:
As you can see, accountMapperItems
list has four positions instead of two. First pair is a duplicate each having the same variables. (second is similar, not shown on screenshot).
Below I paste entities code fragments:
class AccountGroup {
...
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "group")
private List<AccountItem> accountMapperItems;
....
}
class AccountItem {
...
@ManyToMany(fetch = FetchType.EAGER, cascade = { CascadeType.REFRESH, CascadeType.MERGE })
@JoinTable(
joinColumns={@JoinColumn(name="ACCOUNT_ITEM_ID", referencedColumnName="ID")},
inverseJoinColumns={@JoinColumn(name="SEGMENT_ID", referencedColumnName="ID")})
private Set<Segment> segmentSet;
@ManyToOne
private AccountGroup group;
...
}
AccountSegment
does not have any links.
Does anyone know why is it retriving accountMapperItems
list one position per AccountSegment
?
The problem is not duplicate entries in jointable! I have double checked it.
Update
@Fetch (FetchMode.SELECT)
solved the case, further explanations are available in post mentioned in the answer.
Upvotes: 1
Views: 926
Reputation: 22451
Make sure all your entities implement hashCode()
and equals()
. These methods are used by some collections (like Sets) to uniquely identify elements.
Edit: If that doesn't solve it, then I think the duplicates are most likely caused by the FetchType.EAGER
. This answer explains it well. Try removing the FetchType.EAGER
to see if it makes any difference.
Upvotes: 3