Persistence top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

When working with Hibernate, we can use named parameters to safely pass data into an SQL query. We assign values to query parameters at runtime to make them dynamic. More importantly, this helps prevent SQL injection attacks.

However, we may encounter errors when working with named parameters. Two of the more common ones from Hibernate's standalone library and the Hibernate JPA implementation, respectively, are:

  • Not all named parameters have been set
  • Named parameter not bound

Although the error messages may differ between vanilla Hibernate and its JPA implementation, the root cause is the same.

In this tutorial, we'll take a look at what causes these errors and how to avoid them. Along the way, we'll demonstrate how to use named parameters with Hibernate's standalone library.

2. What Causes the Error

When working with named parameters in Hibernate, we must assign a value to each named parameter before executing the query.

Let's look at an example of a query that uses a named parameter:

Query<Event> query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class);

In this example, we have one named parameter, indicated by the :eventTitle placeholder. Hibernate expects this parameter to be set before we execute the query.

However, if we try to execute the query without setting the value for :eventTitle:

List<Event> listOfEvents = query.list();

Hibernate will throw org.hibernate.QueryException when we run it, and we'll get the error:

Not all named parameters have been set

3. Fixing the Error

To fix the error, we simply provide a value for the named parameter before executing the query:

Query<Event> query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class);
query.setParameter("eventTitle", "Event 1");
 
assertEquals(1, query.list().size());

By using the setParameter(String, String) method of the query object, we tell Hibernate which value we want to use for the named parameter.

4. Conclusion

In this article, we looked at named parameters and how they are used in Hibernate. We also showed how to fix one of the named query errors we might run into.

As usual, all the code samples are available over on GitHub.

Persistence bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of