Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How entity comparison works in JPQL WHERE clause?

How is entities comparison (equality) statement evaluated in JPQL: is it by identity comparison, or by equals(), or sth else?

I've spent a couple of hours of googling and going through the specs of Hibernate and JPA but still can't find how it works. Consider the following entities:

class MyProductType{Integer id;}
class MyProduct{Integer id; MyProductType pType;}

And now the JPQL/HQL query:

SELECT t FROM MyProductType t, MyProduct p WHERE p.pType = t

(I know it's an ugly query, just focus on the where clause semantics.)

So how is p.pType = t evaluated?

JSR 317 mentions "entity_expression" comparison but it's behaviour is not clarified.

EDIT: What I dislike about Rika's suggestion below is that the .id approach includes implicit inner join which is usually not what you want in case the query employs an OUTER (LEFT) join.

like image 705
sierre Avatar asked Oct 10 '14 13:10

sierre


People also ask

Which of the following clauses are supported in JPQL?

JPQL can retrieve information or data using SELECT clause, can do bulk updates using UPDATE clause and DELETE clause.

What is the difference between JPA and JPQL?

The main difference between JPQL and SQL lies in that the former deals with JPA entities, while the latter deals directly with relational data.

Which among the following is are features of JPQL?

JPQL FeaturesIt is a platform-independent query language. It is simple and robust. It can be used with any type of database such as MySQL, Oracle. JPQL queries can be declared statically into metadata or can also be dynamically built in code.

Which methods should be used for pagination with JPQL?

For all JPA query objects (except for native SQL queries), you would use pagination through the setMaxResults(int) and setFirstResult(int) methods.


1 Answers

I found this at http://www.objectdb.com/java/jpa/query/jpql/comparison, it is very interesting, good question.

Instances of user defined classes (entity classes and embeddable classes) can be compared by using the equality operators (=, <>, ==, !=). For entities, e1 = e2 if e1 and e2 have the same type and the same primary key value. For embeddable objects, e1 = e2 if e1 and e2 have exactly the same content.

So it seems it checks the primary key value of the objects and the type of the objects. So it seems with p.pType = t, it will check the (assuming the id is the primary key) the id of p.pType, with the id of t and see if they are equal. Then it will check to see if both entities are of the same type or MyProductType.

like image 73
Rika Avatar answered Sep 28 '22 01:09

Rika