Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Query Hints to spring data jpa querydsl queries?

I'm using Spring Data JPA 1.7.1

I was trying pass query hints (e.g. for Hibernate query caching) to queries when using the querydsl methods of the standard Spring Data repositories, as defined in the QueryDslPredicateExecutor interface, e.g. findOne(Predicate predicate), findAll(Predicate predicate) etc.

I figured that they can be set by overriding the methods in QueryDslPredicateExecutor (in my repository interface or an intermediate interface) and adding the QueryHints annotation, but since I cannot find this documented anywhere I was wondering if this is the recommended way of doing it.

Here is an example:

public interface MyEntityRepository extends CrudRepository<MyEntity, Integer>, CacheableQueryDslPredicateExecutor<MyEntity> {

    @QueryHints(value = {
            @QueryHint(name = "org.hibernate.cacheable", value = "true"),
            @QueryHint(name = "org.hibernate.cacheMode", value = "NORMAL"),
            @QueryHint(name = "org.hibernate.cacheRegion", value = "myCacheRegion")
    })
    Iterable<T> findAll(Predicate predicate);

}
like image 681
Nazaret K. Avatar asked Mar 10 '15 13:03

Nazaret K.


People also ask

What is Querydsl in Spring data JPA?

Querydsl is an extensive Java framework, which helps with creating and running type-safe queries in a domain specific language that is similar to SQL. In this article we'll explore Querydsl with the Java Persistence API.

How can you configure JPQL query for a query method in a repository in Spring data JPA?

In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.

What is query hints in JPA?

The JPA query hints mechanism allows you to customize the way a given query is executed by Hibernate. For instance, you can specify a timeout threshold or specify that the returned entities should be fetched in read-only mode.

How do you write dynamic native SQL query in Spring data JPA?

If you need to write dynamic queries to retrieve a single JPA entity, you would need to implement: <T> T findOne(QueryCallback<T> callback); If you need to write dynamic queries with pagination support, you would need to implement: <T> Page<T> findAll(Pageable pageable, QueryCallback<Page<T>> callback);


1 Answers

This is the recommended and correct way of doing it, see documentation for 1.7.1:

http://docs.spring.io/spring-data/jpa/docs/1.7.1.RELEASE/reference/html/#jpa.query-hints

like image 126
Michael Simons Avatar answered Oct 12 '22 21:10

Michael Simons