为 OneToMany 关系构建 JPA 查询

发布于 2024-11-18 10:09:51 字数 318 浏览 4 评论 0原文

我有这 2 个实体

Class A {
    @OneToMany(mappedBy="a")
    private List<B> bs;
}

Class B {

    @ManyToOne
    private A a;

    private String name;
}

1) 我想构造一个查询,表示获取所有至少有一个名称为“mohamede1945”的 B 的 A

2) 我想构造一个查询,表示获取所有没有名称的 A有任何 B 的名字=“mohamede1945”

有人可以帮助我吗?

I've those 2 entities

Class A {
    @OneToMany(mappedBy="a")
    private List<B> bs;
}

Class B {

    @ManyToOne
    private A a;

    private String name;
}

1) I would like to construct a query that says get all A's that have at least one B with name ="mohamede1945"

2) I would like to construct a query that says get all A's that don't have any B with name = "mohamede1945"

Could anyone help me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

跨年 2024-11-25 10:09:51

首先,我认为您可以通过查看此链接并搜索 JOIN 来了解答案:http://download.oracle.com/docs/cd/E11035_01/kodo41/full/html/ejb3_langref.html

第二个所有,这是我的方法:

@Entity
@NamedQueries({
@NamedQuery(name="A.hasBName",query="SELECT a FROM A a JOIN a.b b WHERE b.name = :name"),
@NamedQuery(name="A.dontHasBName",query="SELECT a FROM A a JOIN a.b b WHERE b.name <> :name")
})
Class A { /* as you defined */ }

在您的 DAO 中,您可以像这样创建命名查询:

public List<A> findByHasBName( String name ){
    Query q = em.createNamedQuery("A.hasBName")
            .setParameter("name", name);
    try{
        return ( (List<A>) q.getResultList());
    } catch ( IndexOutOfBoundsException e){
        return null;
    }
}

First of all, I think you can learn the answer by looking at this link and search for JOIN: http://download.oracle.com/docs/cd/E11035_01/kodo41/full/html/ejb3_langref.html

Second of all, here is my approach:

@Entity
@NamedQueries({
@NamedQuery(name="A.hasBName",query="SELECT a FROM A a JOIN a.b b WHERE b.name = :name"),
@NamedQuery(name="A.dontHasBName",query="SELECT a FROM A a JOIN a.b b WHERE b.name <> :name")
})
Class A { /* as you defined */ }

In you DAO, you can make the namedquery like this:

public List<A> findByHasBName( String name ){
    Query q = em.createNamedQuery("A.hasBName")
            .setParameter("name", name);
    try{
        return ( (List<A>) q.getResultList());
    } catch ( IndexOutOfBoundsException e){
        return null;
    }
}
枉心 2024-11-25 10:09:51

您可以使用 ANY 和 ALL 结构来过滤子查询。所以像

1. FROM A aEntity WHERE 'mohamede1945' = ANY (SELECT bEntity.name FROM aEntity.bs bEntity)

2. FROM A aEntity WHERE 'mohamede1945' <> ALL (SELECT bEntity.name FROM aEntity.bs bEntity)

You can use the ANY and ALL constructs to filter the subquery. So something like

1. FROM A aEntity WHERE 'mohamede1945' = ANY (SELECT bEntity.name FROM aEntity.bs bEntity)

2. FROM A aEntity WHERE 'mohamede1945' <> ALL (SELECT bEntity.name FROM aEntity.bs bEntity)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文