Construct JPA query for a OneToMany relation

前端 未结 2 1268
既然无缘
既然无缘 2020-12-10 06:58

I\'ve those 2 entities

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

Class B {

    @ManyToOne
    private A a;

    private Stri         


        
相关标签:
2条回答
  • 2020-12-10 07:48

    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)
    
    0 讨论(0)
  • 2020-12-10 07:51

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题