Hibernate内连接在关联上的使用(通过注解)

huangapple go评论69阅读模式
英文:

Hibernate Inner Join on Association Through Annotation

问题

有没有办法通过注解强制 Hibernate 在关联中使用内连接?我正在使用基于 Spring Boot JPA 的 Hibernate 5。

@Data
class Entity {
 private Integer id;

 @OneToMany
 @JoinColumn(name="entityId", referencedColumnName="id")
 private Set<ComplexObject> complexObjects;

我希望 complexObjects 的连接是内连接,而不是左连接。

英文:

Is there any way to force hibernate to use an inner-join for an association using annotations? I am using Hibernate 5 via Spring Boot JPA

@Data
class Entity {
 private Integer id;

 @OneToMany
 @JoinColumn(name=&quot;entityId&quot;, referencedColumnName=&quot;id&quot;)
 private Set&lt;ComplexObject&gt; complexObjects;


I would like the join for complexObjects be an inner-join rather than a left join.

答案1

得分: 1

因为这是一个默认为惰性加载的@OneToMany关联,所以默认情况下你不应该看到任何连接操作。必须明确地使用LEFT JOIN FETCH或者只使用LEFT JOIN来执行查询。导致执行左连接的其他可能原因包括使用实体图(entity graph)或在JPA CriteriaBuilder API中使用fetch方法。

通常情况下,这里的左连接是正确的,因为保留预期的基数是必要的。如果使用内连接进行提取,如果没有子项,将会消除主实体,这可能不符合人们在应用实体图时的预期。

我不明白为什么你需要一个INNER JOIN,但是根据连接是如何创建的,你可能需要调整查询以获得所需的结果。

英文:

You shouldn't see a join by default at all since this is a @OneToMany association which is lazy by default. There must be a query explictly using LEFT JOIN FETCH or just LEFT JOIN. Other possible reasons for left joins to happen are the use of an entity graph or the use of the fetch method in the JPA CriteriaBuilder API.

In general, the left join here is correct as it is necessary to retain the expected cardinality. Fetching with an inner join would eliminate the main entity if there were no children which is probably not what one would expect when applying e.g. an entity graph.

I don't understand why you need an INNER JOIN, but depending on how the join is created, you might have to adapt your query to get the desired result.

huangapple
  • 本文由 发表于 2020年8月18日 00:12:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63454686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定