英文:
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="entityId", referencedColumnName="id")
private Set<ComplexObject> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论