1. Introduction
1.绪论
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.
在使用Hibernate时,我们可以使用命名参数来安全地将数据传入SQL查询。我们在运行时为查询参数赋值,使其成为动态参数。更重要的是,这有助于防止SQL注入攻击。
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:
然而,我们在处理命名参数时可能会遇到错误。来自Hibernate独立库和Hibernate JPA实现的两个比较常见的错误分别是。
- 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.
尽管vanilla Hibernate和其JPA实现之间的错误信息可能不同,但根本原因是相同的。
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.
在本教程中,我们将看看是什么导致了这些错误以及如何避免它们。在此过程中,我们将演示如何在Hibernate的独立库中使用命名参数。
2. What Causes the Error
2.导致错误的原因
When working with named parameters in Hibernate, we must assign a value to each named parameter before executing the query.
在Hibernate中使用命名参数时,我们必须在执行查询之前为每个命名参数分配一个值。
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.
在这个例子中,我们有一个命名参数,由:eventTitle占位符表示。Hibernate希望这个参数在我们执行查询之前被设置。
However, if we try to execute the query without setting the value for :eventTitle:
然而,如果我们试图在不设置:eventTitle值的情况下执行查询。
List<Event> listOfEvents = query.list();
Hibernate will throw org.hibernate.QueryException when we run it, and we’ll get the error:
当我们运行它时,Hibernate会抛出org.hibernate.QueryException,我们会得到这个错误。
Not all named parameters have been set
3. Fixing the Error
3.纠正错误
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.
通过使用query对象的setParameter(String, String) 方法,我们告诉Hibernate我们要为命名的参数使用哪个值。
4. Conclusion
4.总结
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.
在这篇文章中,我们研究了命名参数以及它们在Hibernate中的使用方式。我们还展示了如何修复我们可能遇到的一个命名查询错误。
As usual, all the code samples are available over on GitHub.
像往常一样,所有的代码样本都可以在GitHub上找到。