Settings to avoid
You should not use this setting:
spring.jpa.show-sql=true
The problem with show-sql
is that the SQL statements are printed in the console, so there is no way to filter them, as you'd normally do with a Logging framework.
Using Hibernate logging
In your log configuration file, if you add the following logger:
<logger name="org.hibernate.SQL" level="debug"/>
Then, Hibernate will print the SQL statements when the JDBC PreparedStatement
is created. That's why the statement will be logged using parameter placeholders:
INSERT INTO post (title, version, id) VALUES (?, ?, ?)
If you want to log the bind parameter values, just add the following logger as well:
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>
Once you set the BasicBinder
logger, you will see that the bind parameter values are logged as well:
DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]
Using datasource-proxy
The datasource-proxy OSS framework allows you to proxy the actual JDBC DataSource
, as illustrated by the following diagram:
You can define the dataSource
bean that will be used by Hibernate as follows:
@Bean
public DataSource dataSource(DataSource actualDataSource) {
SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
return ProxyDataSourceBuilder
.create(actualDataSource)
.name(DATA_SOURCE_PROXY_NAME)
.listener(loggingListener)
.build();
}
Notice that the actualDataSource
must be the DataSource
defined by the [connection pool][2] you are using in your application.
Next, you need to set the net.ttddyy.dsproxy.listener
log level to debug
in your logging framework configuration file. For instance, if you're using Logback, you can add the following logger:
<logger name="net.ttddyy.dsproxy.listener" level="debug"/>
Once you enable datasource-proxy
, the SQl statement are going to be logged as follows:
Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]