获取具有一对多关系的所有实体,其中一个相关实体符合条件

时间:2016-05-11 20:00:22

标签: jpa hql jpql

我需要根据一对多关系中相关记录的约束来获取记录。例如,我有:

@Entity
@Table (name = "LISTING")
public class Listing
{
    @Id
    @GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "LISTING_SEQ")
    @SequenceGenerator (name = "LISTING_SEQ", initialValue = 1, allocationSize = 1, sequenceName = "LISTING_SEQ")
    @Column (unique = true, nullable = false, updatable = false)
    long id;

    @OneToMany (mappedBy = "listing", fetch = FetchType.EAGER)
    Set<ListingLineItem> listingLineItems;

    ...
}

和....

@Entity
@Table (name = "LISTING_LINE_ITEM")
public class ListingLineItem
{
    @EmbeddedId
    ListingLineItemPK         id;

    boolean ignored;

    @ManyToOne (fetch = FetchType.EAGER)
    @JoinColumn (name = "listing_id", nullable = false)
    Listing                   listing;

    ...
}

我需要编写一个JPQL / HQL查询或使用CriteriaBuilder给我Listing个有相关的ListingLineItem,其中ignore = true。

1 个答案:

答案 0 :(得分:0)

这里是jpql中的解决方案:

SELECT l FROM Listing l, ListingLineItem lli 
WHERE lli.listing.id = l.id AND lli.ignored = true