An alternative approach is to use a proxy driver such as log4jdbc2 which has the advantage of logging the exact SQL going to the database with parameters in place unlike the other answers. This will work regardless of the persistence abastraction layer (e.g. iBatis, JPA etc).
https://code.google.com/archive/p/log4jdbc-log4j2/
One major convenience of this is that you can copy the SQL straight to your DB front-end and execute as is.
1 Add Maven Dependencies:
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
2 Add logback configuration. Copy the relevant parts to your existing logback.xml
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="jdbc.audit" level="ERROR" />
<logger name="jdbc.connection" level="ERROR" />
<logger name="jdbc.sqltiming" level="ERROR" />
<logger name="jdbc.resultset" level="ERROR" />
<!-- UNCOMMENT THE BELOW TO HIDE THE RESULT SET TABLE OUTPUT -->
<!--<logger name="jdbc.resultsettable" level="ERROR" /> -->
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
3 Tell log4jdbc2 about your logging config:
Create a file named log4jdbc.log4j2.properties at the root of the classpath src/test/resources or src/main/resources in a Maven project. This file has one line which is the below:
log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator
4 Change your DB driver class and URL as below:
spring.database.driverClassName=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
#append log4jdbc after jdbc part of the URL: hsql example
spring.datasource.url=jdbc:log4jdbc:hsqldb:mem:db_name
In addition to logging SQL it will also log, in tabular format, the results of all queries executed. This can be disabled as per the comment in the sample logging config.
Sample Output:
10:44:29.400 [main] DEBUG jdbc.sqlonly -
5. select memberrole0_.member_id as member_i2_12_0_, memberrole0_.id as id1_12_0_, memberrole0_.id
as id1_12_1_, memberrole0_.member_id as member_i2_12_1_, memberrole0_.role_id as role_id3_12_1_,
role1_.id as id1_17_2_, role1_.name as name2_17_2_ from member_roles memberrole0_ left outer
join roles role1_ on memberrole0_.role_id=role1_.id where memberrole0_.member_id=104
10:44:29.402 [main] INFO jdbc.resultsettable -
|----------|---|---|----------|--------|---|-----|
|member_id |id |id |member_id |role_id |id |name |
|----------|---|---|----------|--------|---|-----|
|----------|---|---|----------|--------|---|-----|