W3docs

Hibernate show real SQL

To show the real SQL generated by Hibernate, you can enable the show_sql property in the Hibernate configuration file (hibernate.cfg.xml).

To show the real SQL generated by Hibernate, you can enable the hibernate.show_sql property in the Hibernate configuration file (hibernate.cfg.xml). This will cause Hibernate to log all the SQL statements it generates to the console or to a log file.

Here is an example of how you can enable the hibernate.show_sql property in the Hibernate configuration file:


<property name="hibernate.show_sql">true</property>

Alternatively, you can enable the hibernate.show_sql property programmatically using the setProperty() method of the Configuration class.

Here is an example of how you can enable the hibernate.show_sql property programmatically:


Configuration config = new Configuration();
config.setProperty("hibernate.show_sql", "true");

Keep in mind that enabling the hibernate.show_sql property can have a negative impact on the performance of your application, as it causes Hibernate to log all the SQL statements it generates. You should only enable the hibernate.show_sql property for debugging purposes and disable it in production.

Note: The show_sql property and Configuration class are deprecated in Hibernate 5.x and 6.x. For modern applications, consider using Spring Boot properties (spring.jpa.show-sql=true), EntityManagerFactory configuration, or configuring the org.hibernate.SQL logger via SLF4J/Logback.

You can also retrieve the query string using the Query class.

For example:


Query query = session.createQuery("from Employee");
String queryStr = query.getQueryString();

This will return the HQL/JPQL string used by Hibernate. Note that SQLQuery.getSQL() is deprecated and removed in Hibernate 6; use logging or hibernate.format_sql=true to inspect the actual generated SQL.