Hibernate与OneToMany关系的奇怪行为

时间:2022-09-11 16:30:47

My code is involving 3 entities:

我的代码涉及3个实体:

@Entity
public class Data implements Serializable {
    ...
    @OneToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER,
               targetEntity = Bit.class,mappedBy = "data")
    private Collection<Bit> bit;    

    @OneToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER,
               targetEntity = Linked.class,mappedBy = "data")
    private Collection<Linked> linked;
}

@Entity
public class Linked implements Serializable {
    ...
    @EmbeddedId
    private LinkIdPK id;

    @ManyToOne(optional=true,fetch = FetchType.EAGER,targetEntity = Data.class)
    private Data data;
}

@Entity
public class Bit implements Serializable {
    ...
    @EmbeddedId
    private BitIdPK id;

    @MapsId("data")@ManyToOne(optional=true,targetEntity = Data.class)
    private Data data;

I'm performing a search using a Spring repository in order to get one instance of Data. I know that the element I'm querying from the database has "3 Bit" elements, and "1 Linked" element in the database.

我正在使用Spring存储库执行搜索,以获取一个Data实例。我知道我从数据库查询的元素有“3 Bit”元素,数据库中有“1 Linked”元素。

When I loop over the Bit elements in Data.bit, I find 3 elements, which is normal.

当我遍历Data.bit中的Bit元素时,我找到3个元素,这是正常的。

But when I loop over the Linked elements in Data.linked, I find 3 elements, which are pointing to the same object, whereas I was expecting only 1 element.

但是当我遍历Data.linked中的Linked元素时,我找到了3个元素,它们指向同一个对象,而我只期待1个元素。

I have tried adding 1 Bit element in the database, and now I find 4 elements in Data.linked pointing to the same object.

我尝试在数据库中添加1位元素,现在我在Data.linked中找到4个指向同一对象的元素。

Is it a normal behaviour ? Is it a bug in my code, or is it a bug in Hibernate ?

这是正常的行为吗?这是我的代码中的错误,还是Hibernate中的错误?

2 个解决方案

#1


@MapsID on the many to one mapping of Linked to Data is missing.It may be causing the issue as you are using embedded id.

关于链接到数据的多对一映射的@MapsID丢失。当您使用嵌入式ID时,可能会导致问题。

Regards,

Prasad

#2


Finally, I got an answer from the hibernate team. It seems this is a known issue, and there is only a workaround for it, for now: Add the annotation @Fetch(value = FetchMode.SUBSELECT) to one of the OneToMany collections.

最后,我从hibernate团队得到了答案。这似乎是一个已知问题,目前只有一种解决方法:将注释@Fetch(value = FetchMode.SUBSELECT)添加到其中一个OneToMany集合中。

#1


@MapsID on the many to one mapping of Linked to Data is missing.It may be causing the issue as you are using embedded id.

关于链接到数据的多对一映射的@MapsID丢失。当您使用嵌入式ID时,可能会导致问题。

Regards,

Prasad

#2


Finally, I got an answer from the hibernate team. It seems this is a known issue, and there is only a workaround for it, for now: Add the annotation @Fetch(value = FetchMode.SUBSELECT) to one of the OneToMany collections.

最后,我从hibernate团队得到了答案。这似乎是一个已知问题,目前只有一种解决方法:将注释@Fetch(value = FetchMode.SUBSELECT)添加到其中一个OneToMany集合中。