Search code examples
jpanamed-query

JPA NamedQuery to obtain a referenced object without executing join


Say I have three entities: Customer, Product and Order. Each Order has a ManyToOne association to a Customer and a ManyToOne association to a Product. Associations are unidirectional from Order to Customer and to Product respectively. So the database looks like:

Customer
+----+-----+
| ID | ... |
+----+-----+

Product
+----+-----+
| ID | ... |
+----+-----+

Order
+----+-------------+------------+-----+
| ID | CUSTOMER_ID | PRODUCT_ID | ... |
+----+-------------+------------+-----+

Now I want to write a NamedQuery to retrieve all the Customer who ordered a particular Product. Can I refer the Customer object in the query without executing a join between Customer and Order? Can I write something like:

@NamedQuery(
name =  "GetCustomersByProduct",
query = "SELECT o.customer"
        "FROM Order o "+
        "WHERE  o.productId = :productId"
)

Or is it necessary to execute a join? What's the best way to do this?


Solution

  • Your query is right and only thing you need to get distinct customer since same product customer may have ordered more than once

    query = "SELECT distinct(o.customer)"
        "FROM Order o "+
        "WHERE  o.productId = :productId"
    

    Get Customer :

        Query qry = em.createNamedQuery("GetCustomersByProduct");
        List<Customer> resultList = qry.getResultList();