I'm building a SpringBoot application with spring-data-jpa. I know how to log all sqls from this question. How to print a query string with parameter values when using Hibernate
But what if I only want to log failed sqls?
Hibernate has build-in a function to enable the logging of all the generated SQL statements to the console. You can enable it by add a “show_sql” property in the Hibernate configuration file “ hibernate. cfg. xml “.
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.
There are two options:
First, let's analyze the problem and split the query types into SELECT and INSERT/UPDATE queries.
A solution to your problem needs to do essentially two things: 1. It should log the queries with their parameter values. This can be done the following way:
# logs the SQL statements
log4j.logger.org.hibernate.SQL=debug
# Logs the JDBC parameters passed to a query
log4j.logger.org.hibernate.type=trace
2. The solution needs to disable the batching of queries, otherwise, you will get a bunch of SQLs but you will not know which SQL exactly is the problematic one.
hibernate.jdbc.batch_size=1
Not sure if this will be enough to entirely disable the batching, but you need to find out.
Alternatively, you can use a jdbc driver designed for DEBUG. This would be p6spy driver which has the option to flush every single SQL statement which is exactly what you want.
Here you need to set the autoflush=true
configuration parameter to ensure every single sql statement is immediately flushed to the database.
https://p6spy.readthedocs.io/en/latest/configandusage.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With