• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

Thoughts on Java

  • Tutorials ▼
    • Hibernate & JPA Tutorials
    • Hibernate Tips
    • Tutorials on YouTube
  • Books & Training ▼
    • Hibernate Tips Book
    • Online Training
    • On-Site Training
  • Consulting ▼
    • Consulting Call
    • Project Coaching
  • About ▼
    • About Thoughts on Java
    • Support Thoughts on Java
    • Resources
  • Member Library
You are here: Home / Featured / 11 JPA and Hibernate query hints every developer should know
Special thanks to all Thoughts on Java Supporters for supporting this article!

11 JPA and Hibernate query hints every developer should know

By Thorben Janssen 7 Comments

  • tweet 
  • share 
  • share 
  • share 
  • share 
  • share 
  • e-mail 

11 JPA and Hibernate query hints

JPA and Hibernate support a set of hints which you can use to provide additional information to your persistence provider to influence the execution of a query. You can use them for lots of different things, like setting a timeout for your query, using an entity graph or defining the caching of a query result.

 

How to use query hints

But before we start with the list of hints, let’s have a quick look at how you can use a query hint. You can provide it to the EntityManager.find method, the Query interface for named and ad-hoc queries or the definition of a @NamedQuery. The only sad thing about this is that the syntax for each of them is a little bit different.

The EntityManager.find method accepts a HashMap<String, Object> as an additional parameter to provide the hints.

EntityGraph<?> graph = em.getEntityGraph(“graph.AuthorBooks”);

HashMap<String, Object> properties = new HashMap<>();
properties.put(“javax.persistence.fetchgraph”, graph);

em.find(Author.class, 1L, properties);

The Query interface provides the setHint(String name, Object value) method which you have to call for each hint you want to provide.

EntityGraph<?> graph = em.getEntityGraph(“graph.AuthorBooks”);

em.createQuery(“SELECT a FROM Author a”)
  .setHint(“javax.persistence.fetchgraph”, graph)
.getResultList();

 

And you can also provide hints to the @NamedQuery annotation to add them to the definition of the named query.

@NamedQuery(name = “selectAuthors”, query = “SELECT a FROM Author a”, 
hints = @QueryHint(name = QueryHints.COMMENT, value = “a custom SQL comment”))

In this case, the hints will be used for each instantiation of this named query and you don’t have to set them on the Query interface.

em.createNamedQuery(“selectAuthors”).getResultList();



Already a member? Login here.


 

JPA Hints

Let’s start with the hints defined by the JPA specification:

1. javax.persistence.lock.timeout (Long – milliseconds)

This hint defines the timeout in milliseconds to acquire a pessitimistic lock.

2. javax.persistence.query.timeout (Long – milliseconds)

The javax.persistence.query.timeout hint defines how long a query is allowed to run before it gets canceled. Hibernate doesn’t handle this timeout itself but provides it to the JDBC driver via the JDBC Statement.setTimeout method.

3. javax.persistence.cache.retrieveMode (CacheRetrieveMode – USE | BYPASS)

The retrieveMode hint supports the values USE and BYPASS and tells Hibernate if it shall USE the second-level cache to retrieve an entity or if it shall BYPASS it and get it directly from the database.

4. javax.persistence.cache.storeMode (CacheStoreMode – USE | BYPASS | REFRESH)

This hint defines how Hibernate shall write changed entities to the second-level cache. It can either USE the cache to add entities to the cache and updated existing ones, or BYPASS it for entities that are not already stored in the cache and only update the existing ones or REFRESH the entities located in the cache before they get retrieved from it.

5. javax.persistence.loadgraph (EntityGraph)

The javax.persistence.loadgraph hint allows you to provide an entity graph as a load graph to the query to define eager fetching specifically for this query.

You can read more about entity graphs in JPA 2.1 Entity Graph – Part 1: Named entity graphs and JPA 2.1 Entity Graph – Part 2: Define lazy/eager loading at runtime.

6. javax.persistence.fetchgraph (EntityGraph)

You can use this hint to provide an entity graph as a fetchgraph to a query.

You can read more about entity graphs in JPA 2.1 Entity Graph – Part 1: Named entity graphs and JPA 2.1 Entity Graph – Part 2: Define lazy/eager loading at runtime.



Already a member? Login here.


 

Hibernate Hints

These were the most important query hints defined by the JPA specification. Let’s continue with the Hibernate-specific ones.

7. org.hibernate.flushMode (FlushMode – AUTO | ALWAYS | COMMIT | MANUAL)

If you modify an entity, Hibernate keeps these changes in the first-level cache until it gets flushed. By default, this happens before each query but you can control it by providing a value of the org.hibernate.FlushMode enum as the org.hibernate.flushMode hint. You can choose between:

  • AUTO = Hibernate decides if the changes have to be written to the database,
  • ALWAYS = the Session gets flushed before every query,
  • COMMIT = Hibernate will not write any changes to the database until the transaction gets commited,
  • MANUAL = you have to flush the Session yourself.

8. org.hibernate.readOnly (boolean)

If you will not apply any changes to the selected entities, you can set the org.hibernate.readOnly hint to true. This allows Hibernate to deactivate dirty checking for these entities and can provide a performance benefit.

9. org.hibernate.fetchSize (Long – number of records)

Hibernate provides the value of this hint to the JDBC driver to define the number of rows the driver shall receive in one batch. This can improve the communication between the JDBC driver and the database, if it’s supported by the driver.

10. org.hibernate.comment (String – custom comment)

If you set the hibernate.use_sql_comments property in your persistence.xml file to true, Hibernate generates a comment for each query and writes it to the log file. This can be useful, if you have to analyze huge or complex SQL logs.

You can use the org.hibernate.comment hint to provide your own comment for a query.

11. org.hibernate.cacheable

If you want to use Hibernate’s query cache, you have to activate it in the persistence.xml file and enable it for a specific query by setting the org.hibernate.cacheable hint to true.

 

Summary and cheat sheet

As you have seen, JPA and Hibernate provide a set of hints which you can use to customize and optimize the execution of a query. Especially the ones related to caching and entity graphs can provide huge performance benefits to your application.


Already a member? Login here.

  • tweet 
  • share 
  • share 
  • share 
  • share 
  • share 
  • e-mail 

Related posts:

  1. Entities or DTOs – When should you use which projection?
  2. Is your query too complex for JPA and Hibernate?
  3. 5 tips to write efficient queries with JPA and Hibernate
  4. Hibernate Tips: What’s the Difference between JOIN, LEFT JOIN and JOIN FETCH
Become a Thoughts on Java Supporter to claim your member perks and to help me write more articles like this.

Filed Under: Featured, Hibernate Advanced, JPA Tagged With: Criteria API, Jpql, Query

Implement Your Persistence Layer with Ease

Learn More About Hibernate

Need Some Help with Your Project?

Reader Interactions

Comments

  1. Artem says

    September 7, 2016 at 11:58 pm

    Very much thanks!

    Reply
  2. akil says

    January 27, 2017 at 3:34 pm

    Thank you very much for this interesting article !

    Reply
    • Thorben Janssen says

      January 28, 2017 at 8:45 am

      You’re welcome!
      I’m glad you like it.

      Reply
  3. ha2liny says

    December 12, 2017 at 4:57 pm

    org.hibernate.cachable: if every develop should know it then they should know it’s actually org.hibernate.cacheable

    Reply
    • Thorben Janssen says

      December 13, 2017 at 6:58 am

      Ooops, thanks for pointing out.
      Typo fixed

      Reply
      • ha2liny says

        December 26, 2017 at 8:28 am

        ty. Now I can C/P from here again 🙂

        Reply
        • Thorben Janssen says

          December 29, 2017 at 4:54 pm

          Awesome 🙂

          Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Join over 10.000 developers
in the
Thoughts on Java Library

Ebooks Sidebar Get free access to ebooks, cheat sheets and training videos.
Join Now!
Don't like ads?
Become a Thoughts on Java Supporter.
Special Launch Price

Let’s Connect


Thorben Janssen
Independent consultant, trainer and author
  • Facebook
  • GitHub
  • Google+
  • LinkedIn
  • Twitter
  • xing
  • YouTube

Speaking at

7th February 2019
JUG Ostfalen (Germany):
Hibernate Tips 'n' Tricks: Typische Probleme schnell gelöst (Talk - German)

19th March 2019
JavaLand 2019 (Germany):
Hibernate Tips 'n' Tricks: Typische Probleme schnell gelöst (Talk - German)

21st March 2019
JavaLand 2019 (Germany):
Hibernate + jOOQ + Flyway = Die besten Frameworks in einem Stack (1-day Workshop - German)

6th-10th May 2019
JAX 2019 (Germany):
Hibernate Workshop: Komplexe Lösungen jenseits von CRUD (2-day Workshop - German)

6th-10th May 2019
JAX 2019 (Germany):
Spring Data JDBC vs. Spring Data JPA – Wer macht das Rennen? (Talk - German)

6th-10th May 2019
JAX 2019 (Germany):
Microservices mit Hibernate – typische Probleme und Lösungen (Talk - German)

Looking for an on-site training?

Featured Post

14 YouTube Channels You Should Follow in 2019

Getting Started With Hibernate

Entities or DTOs – When should you use which projection?

Ultimate Guide – Association Mappings with JPA and Hibernate

Ultimate Guide to JPQL Queries with JPA and Hibernate

Recent Posts

  • Hibernate Tips: How to Customize a Constructor Expression for Different Subclasses
  • Hibernate Tips: How to Map java.time.Year with JPA and Hibernate
  • Why, When and How to Use DTO Projections with JPA and Hibernate
  • Hibernate Tip: Map a bidirectional one-to-one association with shared composite primary key
  • Implementing the Repository pattern with JPA and Hibernate
  • Hibernate Tips: How to Handle NULL Values while Ordering Query Results in a CriteriaQuery
  • 6 Hibernate Best Practices for Readable and Maintainable Code
  • Can you use Hibernate/EclipseLink/JPA for your microservice?
  • 14 YouTube Channels You Should Follow in 2019
  • Hibernate Tips: How To Map an Entity to a Query
Don't like ads?
Become a Thoughts on Java Supporter.

Copyright © 2019 Thoughts on Java

  • Impressum
  • Disclaimer
  • Privacy Policy