How does Hibernate handle JPA Criteria API literals

Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!

Introduction

The JPA specification is like a Java interface, However, when it comes to performance, implementation details matter a lot. That’s why, even if you use the JPA standard, you still need to know how the underlying provider implements the standard specification.

For instance, if we take this tweet from Gareth Western:

We can clearly see that there is an issue in the way literals might be handled by Hibernate when executing a Criteria API query.

Therefore, in this article, we are going to see how literals are handled by Hibernate and explain what we have changed in Hibernate 5.2.12.

Domain Model

Let’s assume we have the following JPA entity:

@Entity(name = "Book")
@Table(name = "book")
public class Book {

    @Id
    private Long id;

    private String name;

    @NaturalId
    private long isbn;

    //Getters and setters omitted for brevity
}

For more details about the @NaturalId annotation, check out this article.

And, we have the following Book entry in our database:

Book book = new Book();
book.setId(1L);
book.setName("High-Performance Java Persistence");
book.setIsbn(978_9730228236L);

entityManager.persist(book);

Default literal handling mode

When executing the following Criteria API query:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<Book> cq = cb.createQuery(Book.class);
Root<Book> root = cq.from(Book.class);
cq.select(root);
cq.where(
    cb.equal(
        root.get("isbn"), 
        978_9730228236L
    )
);

Book book = entityManager.createQuery(cq).getSingleResult();

assertEquals(
    "High-Performance Java Persistence", 
    book.getName()
);

Writing JPA Criteria API queries is not very easy. The Codota IDE plugin can guide you on how to write such queries, therefore increasing your productivity.

For more details about how you can use Codota to speed up the process of writing Criteria API queries, check out this article.

Hibernate generates the following SQL query:

SELECT 
    b.id AS id1_0_,
    b.isbn AS isbn2_0_,
    b.name AS name3_0_
FROM 
    book b
WHERE 
    b.isbn = 9789730228236

As expected, the literal value was inlined in the generated SQL query.

However, when using a String literal:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<Book> cq = cb.createQuery(Book.class);
Root<Book> root = cq.from(Book.class);
cq.select(root);
cq.where(
    cb.equal(
        root.get("name"), 
        "High-Performance Java Persistence"
    )
);

Book book = entityManager.createQuery(cq).getSingleResult();

assertEquals(
    978_9730228236L, 
    book.getIsbn()
);

Hibernate generates the following SQL query:

SELECT 
    b.id AS id1_0_,
    b.isbn AS isbn2_0_,
    b.name AS name3_0_
FROM 
    book b
WHERE 
    b.name = ?

The literal is gone! Instead, we now got a PreparedStatement bind parameter.

Now, depending on the use case, you either want to use inlined literal values or substitute them with bind parameters. The advantage of using bind parameters is that the query Parse Tree and the Execution Plan (e.g. Oracle, SQL Server) could be cached.

However, sometimes caching the Execution Plan can cause more harm than good, especially if the literal values are skewed or there is a lot of contention on the Execution Plan Cache.

For this purpose, the HHH-9576 Jira issue was created.

Confguring the literal handling mode

Since Hibernate 5.2.12, you can use the LiteralHandlingMode to define the strategy used for handling literals in Criteria API queries. This enumeration takes three values:

  • AUTO, which works exactly as you’ve just seen. Numeric values are inlined while String-based ones are substituted with bind parameters.
  • INLINE, which will inline both numeric and String-based values.
  • BIND, which will substitute both numeric and String-based literals with bind parameters.

So, if we provide the INLINE handling mode:

properties.put(
    AvailableSettings.CRITERIA_LITERAL_HANDLING_MODE, 
    LiteralHandlingMode.INLINE
);

And, rerun the String-based example, Hibernate will now execute the following SQL query:

SELECT 
    b.id AS id1_0_,
    b.isbn AS isbn2_0_,
    b.name AS name3_0_
FROM 
    book b
WHERE 
    name = 'High-Performance Java Persistence'

Or, if we change it to BIND:

properties.put(
    AvailableSettings.CRITERIA_LITERAL_HANDLING_MODE, 
    LiteralHandlingMode.BIND
);

And rerun the numeric literal example, you will now get the following SQL query:

SELECT 
    b.id AS id1_0_,
    b.isbn AS isbn2_0_,
    b.name AS name3_0_
FROM 
    book b
WHERE 
    b.isbn = ?

That’s it!

If you enjoyed this article, I bet you are going to love my Book and Video Courses as well.

Conclusion

Specifying the expected Criteria API literal handling mode is actually a very nice enhancement. While the default AUTO mode might work just fine for many data access layers, in case you need to change the way literals are being handled, just provide the LiteralHandlingMode strategy you want to use, and Hibernate will switch to using that one instead.

FREE EBOOK

6 Comments on “How does Hibernate handle JPA Criteria API literals

  1. So this explains why I’m seeing a bind variable in query; but how do I supply the value.

    I’m trying to concat two columns with a space in between like this;
    Expression nameConcat = cb.function(“concat_ws”, String.class, cb.literal(” “), root.get(PCDetails_.firstName), root.get(PCDetails_.lastName));

    but the where clause comes out like this;
    (concat_ws(?, pco_.first_name, pco_.last_name)

    Any idea how I can get that space in the concat_ws function?

    I’m using Spring JPA spring-boot.version>1.5.10.RELEASE 5.2.12.Final

      • I see that from the article, but is it a global setting or per Criteria Query? Using Spring JPA, is there a specific place to add;

        Map config = super.getConfig();
        config.put(
        AvailableSettings.CRITERIA_LITERAL_HANDLING_MODE,
        LiteralHandlingMode.INLINE
        );

      • It’s a global setting. You can set it in application.properties too.

      • Thanks for the feedback Vlad, I’m just not getting the results. Can you provide the syntax for the application.properties file?

        And the programatic approach with the getConfig method, where am I putting that? I’m not sure what config file and is it happening on start-up?

        I sincerely apologize but this seems so simple, just need to add a literal to my criteria query, but I’m not getting it. Does your book cover this? I’d be glad to purchase a copy.

        Greatly appreciate your feedback.

      • I can surely help you with this task as, luckily, I also provide Consulting services. If you are interested, just send me an email to vlad[at]vladmihalcea[dot].com. Cheers.

Leave a 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.