Вопрос

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?

Это было полезно?

Решение

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();

Другие советы

Good practice to avoid JOIN is usage of exists (see oracle doc: http://docs.oracle.com/html/E24396_01/ejb3_langref.html#ejb3_langref_exists ), most databases optimize EXISTS in compare with JOIN.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top