JPA How to create Query with ManytoOne relationship?

15,676

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();
Share:
15,676
orshachar
Author by

orshachar

DevOps and CI lover

Updated on June 23, 2022

Comments

  • orshachar
    orshachar almost 2 years

    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....

  • orshachar
    orshachar over 13 years
    Great, but now I get this message: "SELECT FROM Message m WHERE m.owner.username = :ownerID: Can only reference properties of a sub-object if the sub-object is embedded"
  • Fil
    Fil over 13 years
    What kind of object is "username"?
  • orshachar
    orshachar over 13 years
    "username" is String - unique per User Entity object. Thanks!
  • Fil
    Fil over 13 years
    If this is a Google App Engine question, this may help: stackoverflow.com/questions/3032406/…
  • orshachar
    orshachar over 13 years
    I didn't understand how to implement it in my case. sorry.