1.定位日志打印的位置,sql最终是在SqlStatementLogger打印的
org.hibernate.engine.jdbc.spi.SqlStatementLogger
//logToStdout对应show_sql,显示sql
//format对应format_sql,sql格式化
//highlight对应highlight_sql,sql关键字高亮显示
@AllowSysOut
public void logStatement(String statement, Formatter formatter) {
if (this.logToStdout || LOG.isDebugEnabled()) {
if (this.format) {
statement = formatter.format(statement);
}
if (this.highlight) {
statement = FormatStyle.HIGHLIGHT.getFormatter().format(statement);
}
}
LOG.debug(statement);
if (this.logToStdout) {
String prefix = this.highlight ? "\u001b[35m[Hibernate]\u001b[0m " : "Hibernate: ";
System.out.println(prefix + statement);
}
}
2.SqlStatementLogger是在JdbcServicesImpl类中初始化的,转到JdbcServicesImpl类
org.hibernate.engine.jdbc.internal.JdbcServicesImpl
public void configure(Map configValues) {
this.jdbcEnvironment = (JdbcEnvironment)this.serviceRegistry.getService(JdbcEnvironment.class);
assert this.jdbcEnvironment != null : "JdbcEnvironment was not found!";
this.multiTenancyStrategy = MultiTenancyStrategy.determineMultiTenancyStrategy(configValues);
boolean showSQL = ConfigurationHelper.getBoolean("hibernate.show_sql", configValues, false);
boolean formatSQL = ConfigurationHelper.getBoolean("hibernate.format_sql", configValues, false);
boolean highlightSQL = ConfigurationHelper.getBoolean("hibernate.highlight_sql", configValues, false);
long logSlowQuery = ConfigurationHelper.getLong("hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS", configValues, 0);
this.sqlStatementLogger = new SqlStatementLogger(showSQL, formatSQL, highlightSQL, logSlowQuery);
this.resultSetWrapper = new ResultSetWrapperImpl(this.serviceRegistry);
}
看到这里我相信你知道怎么去application里面配置了
如果你是.yml,添加配置
spring:
jpa:
properties:
hibernate:
format_sql: true #格式化sql语句
show_sql: true #控制台是否打印
highlight_sql: true #高亮显示sql关键字
如果你是.properties,添加配置
spring.jpa.properties.hibernate.format_sql=true #格式化sql语句
spring.jpa.properties.hibernate.show_sql=true #控制台是否打印
spring.jpa.properties.hibernate.highlight_sql=true #高亮显示sql关键字
如果以上配置后还是无效,你可以在JdbcServicesImpl中打断点调试,看看是否初始化SqlStatementLogger的时候获取到的是你设置的值。
一般无效的原因是你项目里面设置了EntityManagerFactory,在设置EntityManagerFactory的时候会加载一个默认的Properties(这个配置里面默认format_sql、show_sql、highlight_sql都是false),这个properties会覆盖application里面的配置,所以你需要在EntityManagerFactory.setJpaProperties(properties);之前把上面的配置设置进去
properties.setProperty("hibernate.format_sql","true");
properties.setProperty("hibernate.show_sql","true");
properties.setProperty("hibernate.highlight_sql","true");
EntityManagerFactory.setJpaProperties(properties);
//如果有afterProperties这句的话,需要将afterProperties放在setJpaProperties后面执行
//否则配置也不会被覆盖
//EntityManagerFactory.afterProperties(properties);