we have JPA Specifications defined on an entity. I want to convert that specification to JPQL So I can create join it with some other entity. (I tried using parent-child relationship but that's not efficient, and that doesn't allow us to put filtering(specifications) on chile entity). Earlier We were reading from a single table so we had specifications in place that was working fine. Now we need to join this with another entity, For that I want to use JPQL over specifications. I want to convert specification on one table to JPQL and than join it with other entity.
Asked
Active
Viewed 779 times
2 Answers
0
Use @query annotation on your repository method and write your JPQL query inside the @query annotation.
you can refer table names with your entity name inside the @query annotation.

Kabilan S
- 1
- 1
-
Nope, I want to convert existing specifications to JPQL, Like: String jpql = query.where(....); – yagyavrat Aug 06 '18 at 12:14
0
Let say you have User and List entities
In JPQL you will write something like this
public List<User> getUserByName(String username) {
String queryString = "select u from User u where u.name= '"+username+"' ";
Query query = getEntityManager().createQuery(queryString);
return query.getResultList();
}
With JPA and Hibernate older than 5.1
even with JPA 2.1 and Hibernate 5.0 it’s still not possible to join two unrelated entities.
If User and UserAddress are not related to each other
List<Object[]> results = em.createQuery("SELECT u FROM User u, UserAddress ua WHERE u.firstName = ua.firstName AND u.lastName = ua.lastName").getResultList();
Hibernate will transform this as cross join something like this
User user01_ cross join UserAddress useraddress1_
With Hibernate 5.1
Same quesry will be treated as inner Join
List<Object[]> results = em.createQuery("SELECT u FROM User u, UserAddress ua WHERE u.firstName = ua.firstName AND u.lastName = ua.lastName").getResultList();
User user01_ inner Join UserAddress useraddress1_
Other Imp Point:
Using subqueries in the join clause is not allowed. in JPQL, subqueries are only allowed in the WHERE and HAVING part.

MyTwoCents
- 7,284
- 3
- 24
- 52
-
My question is to convert Specification to Query, Is there any way we can do that? Without rewriting Specification to JPQL. – yagyavrat Aug 09 '18 at 08:15