Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

one to many - Construct JPA query for a OneToMany relation

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...