JPQL查询@OneToMany连接到另一个实体的实体

时间:2010-09-29 15:08:11

标签: jpa jpql

有:

class Container {

    @Id
    @Column(name="id")
    protected long id;

    @OneToMany
    @JoinColumn(name="container_id", nullable=false)
    protected Collection<Content> contents = new ArrayList<Content>();

}

class Content {

    @Id
    @Column(name="id")
    protected long id;

    @Column(name="link_id")
    protected long linkId;

}

哪些JPQL查询将获取具有特定ID且具有特定linkId的Container中的内容实体?

1 个答案:

答案 0 :(得分:7)

如果不进行双向关联,您可以这样做:

SELECT c 
FROM Content c, Container container 
WHERE c MEMBER OF container.contents AND c.linkId = :linkId AND container.id = :containerId 

但是使关联双向化会更容易:

SELECT c from Content c 
WHERE c.container.id = :containerId AND c.linkId = :linkId

生成的SQL看起来更好(也更有效)。