【问题标题】:JPA unidirectional ManyToMany - duplicated positions in when retrieving listJPA单向ManyToMany - 检索列表时重复的位置
【发布时间】:2014-03-08 01:28:43
【问题描述】:

我的项目中有以下实体:

  • AccountGroup
  • AccountItem
  • AccountSegment

具有以下关系:

  • AccountGroup 拥有List<AccountItem>

  • AccountItem List<AccountSegment>

一切正常。

当我将最后一个关系更改为:

  • AccountItemSet<AccountSegment>

AccountGroup 从数据库读取的对象看起来很奇怪。如果给定AccountItem 有三个AccountSegments,那么我在AccountGroup 中有三个相同的AccountItems。

来自调试器的镜头可能比我更能说明问题:

如您所见,accountMapperItems 列表有四个位置,而不是两个。第一对是重复的,每个具有相同的变量。 (第二个类似,屏幕截图中没有显示)。

下面我粘贴实体代码片段:

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 没有任何链接。

有谁知道为什么要检索accountMapperItems 列出每个AccountSegment 的一个位置?

问题是joinable中没有重复的条目!我已经仔细检查过了。

更新

@Fetch (FetchMode.SELECT)

解决了这个问题,答案中提到的帖子中提供了进一步的解释。

【问题讨论】:

    标签: java hibernate jpa many-to-many


    【解决方案1】:

    确保您的所有实体都实现hashCode()equals()。一些集合(如 Set)使用这些方法来唯一标识元素。

    编辑:如果这不能解决问题,那么我认为重复很可能是由FetchType.EAGER 引起的。 This answer 解释得很好。尝试删除FetchType.EAGER 看看是否有任何不同。

    【讨论】:

    • AccountSegmentAccountItem 两个对象添加 equals 和 hashcode 方法后,行为保持不变。这两种方法都只基于主键。
    • 您是通过 JPQL 查询检索数据,还是仅使用集合 getter?
    • 我只使用实体管理器方法find(AcountGroup.class, id)检索AccountGroup
    • 谢谢! @Fetch (FetchMode.SELECT) 来自您提供的链接解决了此案!
    猜你喜欢
    • 2016-09-08
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 2017-09-21
    • 2018-01-21
    • 2021-03-03
    相关资源
    最近更新 更多