简体   繁体   中英

Left Join in HQL - Hibernate query

I have 2 entites , each stored in mysql table. 1. productA : {productId(pk) , desc , date} 2. productB : {productId(pk) , quantity,type,date}

I want to run this SQL query:

     select a.* 
     from productA a left join productB b using(productId)   
     where b.productId is null

(return all the products from a that not exists in b)

Is it possible to write this query in Hibernate?

Thank you!!

Is it possible to write this query in Hibernate?

Yes, of course. From JPA specification 2.1 (4.4.5.2 Left Outer Joins) :

LEFT JOIN and LEFT OUTER JOIN are synonymous. They enable the retrieval of a set of entities where matching values in the join condition may be absent. The syntax for a left outer join is

 LEFT [OUTER] JOIN join_association_path_expression [AS] identification_variable [join_condition] 

An outer join without a specified join condition has an implicit join condition over the foreign key relationship corresponding to the join_association_path_expression. It would typically be mapped to a SQL outer join with an ON condition on the foreign key relationship as in the queries below: Java Persistence query language :

 SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p GROUP BY s.name 

SQL :

 SELECT s.name, COUNT(p.id) FROM Suppliers s LEFT JOIN Products p ON s.id = p.supplierId GROUP By s.name 

An outer join with an explicit ON condition would cause an additional specified join condition to be added to the generated SQL: Java Persistence query language:

 SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p ON p.status = 'inStock' GROUP BY s.name 

SQL :

 SELECT s.name, COUNT(p.id) FROM Suppliers s LEFT JOIN Products p ON s.id = p.supplierId AND p.status = 'inStock' GROUP BY s.name 

Note that the result of this query will be different from that of the following query:

 SELECT s.name, COUNT(p) FROM Suppliers s LEFT JOIN s.products p WHERE p.status = 'inStock' GROUP BY s.name 

The result of the latter query will exclude suppliers who have no products in stock whereas the former query will include them.

An important use case for LEFT JOIN is in enabling the prefetching of related data items as a side effect of a query. This is accomplished by specifying the LEFT JOIN as a FETCH JOIN as described below.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM