Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL Query inside spring @Query annotation

I have been trying to understand the difference between HQL and JPQL. The hibernate documentation at here

suggest that writing select is necessary for JPQL but not in HQL. But when I try writing HQL or JPQL inside Query annotation of spring data JPA , both HQL and JPQL works .

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {
    
    @Query(value = "from com.demo.spring.data.jpa.User u")
    public List<User> findAllUsersHQL();
    
    @Query(value = "select u from com.demo.spring.data.jpa.User u")
    public List<User> findAllUsersJPQL();
}

My understanding is since the Query annotation is intended for JPA why is HQL supported ?

Or let me put in other words -

Can we write HQL in the Query annotation - Does spring data JPA supports both ?

like image 429
Akshay Avatar asked Oct 27 '25 06:10

Akshay


1 Answers

I think it depends on which JPA impleemntation you use.

Even though Spring data says it supports JPQL, Spring data in itself isnt implememnting any functionality for validating and implementing queries with JPQL.

Spring will rely on underlying JPA impleemntation that will validate and convert given JPQL queries into plain SQL.

If the underlying adapter is a hibernate Adapter, There are fair chances that it will support HQL and will not limit the application to JPQL.

Moreover, as jdicker mentioned above, JPQL is a subset of HQL, or in the other words, hibernate provided mucm more functionalty than that of JPA.. so you shoudl be able to parse HQL in spring data as long as you are using Hibernate sa an underlying JPA engine.

DIY - You can try putting a breakpoint in QueryTranslatorImpl and confirm the behavior yourself.

like image 164
Anand Vaidya Avatar answered Oct 29 '25 20:10

Anand Vaidya