开发者

JPA How to create Query with ManytoOne relationship?

The basic question:

If I have an entity B with ManyToOne field x linked to another entity A, how do I get all the instances of B that have A in their x field?

More specifically:

Consider 开发者_如何学运维the following entites:

public class User {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "USER_ID")
 private Key id;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
 private List<Message> messages;
}

ic class Message {
 @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column (name="MESSAGE_ID")
    private Key id;
    @ManyToOne(fetch = FetchType.LAZY)
    private User owner;
    private int status;
}

I already have this query prepared

Query query = em.createQuery("SELECT m from Message m WHERE m.owner = :us");

Here is the api for a method I want to build:

Input: User u, Status s

Output: List of all message with owner u and status s.

I know I am supposed to build a query using EntityMenager but what is the proper syntax? What do I put in the part (*"SELECT m FROM Message m WHERE owner = _ AND status="+status*).

when I tried this:

Query query = em.createQuery("SELECT m from Message m "
+"WHERE m.owner.id = :ownerId");

I got the follwing error:

javax.persistence.PersistenceException: 
SELECT FROM Message m WHERE m.owner.username = :ownerID: 
Can only reference properties of a sub-object if the sub-object is embedded.

Thanks in advance....


You can query against object fields using a '.' notation. For example, you can get the messages with a particular owner by asking for "m.owner.id = ?", or messages with an owner in a specific state by asking for "m.owner.address.state.id = ?"

Query q = em.createQuery(" FROM package.Message m WHERE m.owner.id = :ownerId AND m.status = :status")
            .setParameter("ownerId", user.id)
            .setParameter("status", status)
            .getResultList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜