[英]JPA unidirectional ManyToMany - duplicated positions in when retrieving list
I had following entities in my project: 我的项目中有以下实体:
AccountGroup
AccountItem
AccountSegment
With folowing relations: 随着关系:
AccountGroup
has List<AccountItem>
AccountGroup
具有List<AccountItem>
AccountItem
had List<AccountSegment>
AccountItem
具有 List<AccountSegment>
and everything worked fine. 一切都很好。
When I changed last relation to: 当我将最后一个关系更改为:
AccountItem
has Set<AccountSegment>
AccountItem
具有Set<AccountSegment>
AccountGroup
object read from database looks strange. 从数据库读取的AccountGroup
对象看起来很奇怪。 If given AccountItem
had three AccountSegment
s, then I have three the same AccountItem
s in AccountGroup
. 如果给定的AccountItem
有三个AccountSegment
,那么我在AccountGroup
有三个相同的AccountItem
。
A shot from debugger can possibly tell it better than I can: 来自调试器的镜头可能比我能说得更好:
As you can see, accountMapperItems
list has four positions instead of two. 如您所见, accountMapperItems
列表有四个位置而不是两个。 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. AccountSegment
没有任何链接。
Does anyone know why is it retriving accountMapperItems
list one position per AccountSegment
? 有谁知道为什么它retriving accountMapperItems
列表每一个位置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. 解决了这个案子,在答案中提到的帖子中有进一步的解释。
Make sure all your entities implement hashCode()
and equals()
. 确保所有实体都实现了hashCode()
和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
. 编辑 :如果这没有解决它,那么我认为重复项很可能是由FetchType.EAGER
引起的。 This answer explains it well. 这个答案解释得很好。 Try removing the FetchType.EAGER
to see if it makes any difference. 尝试删除FetchType.EAGER
以查看它是否有任何区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.