为什么这个左连接fetch没有检索条目?

时间:2017-12-29 15:59:54

标签: sql hibernate jpa

我正在尝试编写Hibernate查询来检索给定ID的实体。此实体具有另一个实体的集合,但我只想检索未删除的实体以填充集合:

顶级实体:

@Entity
@Table(name="rss_feed_definition")
public class RSSFeedDefinition extends BaseEntity {

    [...]

    @OneToMany(mappedBy="rssFeedDefinitionId")
    private Collection<RSSFeedProperty> rssFeedProperties;

    [...]

和HQL:

em.createQuery("from RSSFeedDefinition definition left join fetch definition.rssFeedProperties property where property.deleted = false and definition.id = :id");

为什么它不返回RSSFeedDefinition,即使我在属性上加入了(删除标志为true)?

2 个答案:

答案 0 :(得分:1)

JPA不支持JOIN FETCH语句中的任何条件。但在您的情况下,您可以使用以下解决方法:

TypedQuery<RSSFeedDefinition> q = em.createQuery("SELECT definition FROM RSSFeedDefinition definition LEFT JOIN FETCH definition.rssFeedProperties property WHERE property.deleted = false or property.deleted = IS NULL and definition.id = :id", RSSFeedDefinition.class);

如果没有与定义关联的属性,则其属性为null。因此,您需要检查deletedfalse还是null

答案 1 :(得分:0)

我不是Hibernate专家,但在纯SQL中你的问题是:

select * 
from RSSFeedDefinition definition 
left join property on definition.someField = property.otherField 
where property.deleted = false <--- this is the problem because it filters all data
and definition.id = :id

应该是这样的:

select * 
from RSSFeedDefinition definition 
left join property on definition.someField = property.otherField 
                  and property.deleted = false
where definition.id = :id

仅在可以进行连接时进行过滤。