Construct JPA query for a OneToMany relation

╄→гoц情女王★ 提交于 2019-11-28 10:14:28

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)

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!