简体   繁体   English

Hibernate left join fetch on many returns 口是心非

[英]Hibernate left join fetch on many returns duplicities

I have a problem, I am using Hibernate via Spring data and I have this data model (model is much bigger but this is the part that causes problems).我有一个问题,我通过 Spring 数据使用 Hibernate,我有这个数据 model(模型要大得多,但这是导致问题的部分)。

Lets assume we have Entity A and Entity B .假设我们有Entity AEntity B Relationship between two entities are Many-to-Many .两个实体之间的关系是多对多的

I am trying to fetch A records with B recordes fetched (to prevent lazy loading).我正在尝试获取带有B记录的A记录(以防止延迟加载)。

The model is connected like this model是这样连接的

On entity A:在实体 A 上:

@ManyToMany(mappedBy = "items")
private List<BEntity> bs = new ArrayList<>();

On entity B在实体 B 上

@ManyToMany
@JoinTable(
        name = "a_b",
        joinColumns = { @JoinColumn(name = "b_id", referencedColumnName = "id") },
        inverseJoinColumns = { @JoinColumn(name = "a_id", referencedColumnName = "id") }
)
private Collection<AEntity> as = new ArrayList<>();

So its typical M:N relationship.所以它是典型的 M:N 关系。 And I am trying to retrieve A data like following我正在尝试检索 A 数据,如下所示

@Query("SELECT a FROM AEntity a " +
        "   LEFT JOIN FETCH a.bs" +
        "WHERE a.id IN (:aIds)")
List<AEntity> findX(@NonNull @Param("aIds") Collection<Long> aIds);

The resulted SQL is something like结果 SQL 类似于

select X -- select fields omitted for simplicity
from item itembo0_
         left outer join a_b ab on a.id = ab.a_id
         left outer join b b on ab.b_id = b.id
where a.id in (...)

Which is a thing I would expect.这是我所期望的。 The SQL will result duplicites (which I would expect as well cause there might be many B records which each has one result row). SQL 将导致重复(我也希望如此,因为可能有许多 B 记录,每个记录都有一个结果行)。 But at the end, hibernate does not merge all these rows into a A entity with fetched B fields .但最后, hibernate 并没有将所有这些行合并到一个 A entity with fetched B fields中。

For example, when I pass a 5 IDS into "in" condition, I get a 10 A records.例如,当我将 5 IDS 传递到“in”状态时,我得到了 10 A 记录。 Each one has a 2 B records linked!每一个都有2条B记录挂钩! Thats the weird part .那是奇怪的部分

Is there anyone who can tell me why hibernate does not merge these SQL results by A.id identifier and makes duplicites?有谁能告诉我为什么 hibernate 不通过 A.id 标识符合并这些 SQL 结果并生成重复项? Is it because I am asking for a List instead of Set?是因为我要的是 List 而不是 Set 吗?

Using the "DISTINCT" keyword in your query should be enough to avoid duplicates:在查询中使用“DISTINCT”关键字应该足以避免重复:

@Query("SELECT DISTINCT a FROM AEntity a " +
        "   LEFT JOIN FETCH a.bs" +
        "WHERE a.id IN (:aIds)")
List<AEntity> findX(@NonNull @Param("aIds") Collection<Long> aIds);

I do not know what kind of data you store, but perhaps a better solution, as you have mentioned, would be to use a Set instead of a List.我不知道你存储什么样的数据,但正如你所提到的,也许更好的解决方案是使用 Set 而不是 List。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM