I am new in Spring Data JPA
and we have some queries in the project that using JPQL
. I have SQL
knowledge, but as a beginner I need to be clarified about the following questions:
1. What are the options that can be used to create query in Spring Data JPA
? I see Native Query
and a JPQL
, but not sure if there is any other option?
2. What is the difference between a Native Query and a JPQL? I just realized that JPQL
uses class names e.g. ProductCategory while native uses table names e.g. product_category. Is there any other differences?
CodePudding user response:
JPQL will be converted to SQL according to the Entities.
In SQL you write like this:
SELECT d.familyname FROM car c LEFT JOIN driver d ON (c.driver_id = d.id) WHERE c.id = 123
If you have full entities in JPQL you can use:
SELECT d.familyname FROM Car c LEFT JOIN c.driver d WHERE c.id = 123
As you can see, since the entities contains informations about foreign keys, you can shorten the queries.
CONS
The queries have limited language support, non-sql functions from postgres in example are not available.
PROS
The JPQL depends on the entites. If you change the db-vendor the JPQL must not be changed.
Other options (beside JPQL and SQL)
There is something called HQL. But I guess its compleatly compatible to JPQL, so today there is no difference.
EDIT:
You can shorten it much more using this:
SELECT c.driver.familyname FROM Car c WHERE c.id = 123