W3docs

How to print a query string with parameter values when using Hibernate

To print a Hibernate query string with parameter values, you can use the toString() method of the Query interface.

To print a Hibernate query string with parameter values, you can use the toString() method of the Query interface. This method returns a string representation of the query, including the currently bound parameter values.

For example, consider the following Hibernate query:

String hql = "FROM User WHERE username = :username AND password = :password";
Query<User> query = session.createQuery(hql, User.class);
query.setParameter("username", "john");
query.setParameter("password", "123456");

To print the query string with the parameter values, you can use the following code:

System.out.println(query.toString());

This will print the following string:

FROM User WHERE username = 'john' AND password = '123456'

Note that toString() reflects the current parameter state regardless of whether the query has been executed. If parameters have not been bound yet, the placeholders will remain in the output. For more reliable query debugging, consider enabling Hibernate's SQL logging (hibernate.show_sql=true or hibernate.format_sql=true), which automatically prints the final SQL with resolved parameters.

I hope this helps! Let me know if you have any questions.