Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Query optimization by avoiding JOIN to lookup table?

Imagine a table emp:

CREATE TABLE emp
( id           NUMBER
, name         VARCHAR
, dept_code    VARCHAR
)

and a table dept:

CREATE TABLE dept
( code         VARCHAR
, name         VARCHAR
)

emp.dept_code references dept.code as a ForeignKey.

These tables are mapped to JPA Entities, and the ForeignKey is modeled as an association:

@ManyToOne
@JoinColumn(name = "dept_code")
private Department department;

Given following data:

emp                     dept    
----------------        ------------------
1    John   SALS        SALS     Sales
2    Louis  SALS        SUPT     Support
3    Jack   SUPT 
4    Lucy   SUPT  

I would like to write a JPA query that returns all Emloyees in the Support Department. Assume I know the PrimaryKey of the Support Department (SUPT)

I guess that would be:

SELECT emp
  FROM Employee emp JOIN emp.department dept
 WHERE dept.code = 'SUPT'

Question:

As the Department key SUPT code is available in the emp table, is there a way to rewrite the JPA query by avoiding the JOIN to the Department Entity?

Would this result in a performance improvement? Or is a JPA implementation (like Hibernate) smart enough to avoid the database join to the dept table?

like image 562
Jan Avatar asked Sep 07 '10 19:09

Jan


People also ask

Can JPQL join operations?

Instead of database table, JPQL uses entity object model to operate the SQL queries. Here, the role of JPA is to transform JPQL into SQL. Thus, it provides an easy platform for developers to handle SQL tasks. It can perform join operations.

What if there were a tool that could automatically detect JPA and Hibernate performance issues?

Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn't that be just awesome? Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.

Which is JPQL aggregate function?

JPQL supports the five aggregate functions of SQL: COUNT - returns a long value representing the number of elements. SUM - returns the sum of numeric values. AVG - returns the average of numeric values as a double value.


1 Answers

You would usually write the query as

select emp
from employee emp
where emp.department.code = 'SUPT'

and let your provider figure out the best way to come up with the result. In the case of hibernate, yes, it is smart enough to realize it can just look at the join column.

edit : It is worth noting, that you haven't set up lazy loading in your annotations, so it's going to join the table in to create the department entity anyway :)

like image 62
Affe Avatar answered Oct 19 '22 00:10

Affe