我想把SQL语句记录到一个文件中。
我在application.properties中有以下属性:
spring.datasource.url=...
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
security.ignored=true
security.basic.enabled=false
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.file=c:/temp/my-log/app.log
当我运行程序时,
cmd> mvn spring-boot:run
我可以在控制台中看到SQL语句,但它们没有出现在app.log中。该文件只包含Spring的基本日志。
我应该怎么做才能在日志文件中看到SQL语句?
如果要查看实际使用的参数,可以使用查询
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE
然后注意,实际的参数值显示为绑定参数…:
2018-08-07 14:14:36.079 DEBUG 44804 --- [ main] org.hibernate.SQL : select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.joining_date as joining_3_0_, employee0_.name as name4_0_ from employee employee0_ where employee0_.joining_date=?
2018-08-07 14:14:36.079 TRACE 44804 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [TIMESTAMP] - [Tue Aug 07 00:00:00 SGT 2018]
在应用程序中添加spring.jpa.properties.hibernate.show_sql=true。属性并不总是有帮助。
您可以尝试添加properties.put(“hibernate。show_sql”、“真正的”);到数据库配置的属性。
public class DbConfig {
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
Map<String, Object> properties = new HashMap();
properties.put("hibernate.hbm2ddl.auto", "validate");
properties.put("hibernate.show_sql", "true");
return builder
.dataSource(dataSource)
.packages("com.test.dbsource.domain")
.persistenceUnit("dbsource").properties(properties)
.build();
}
如果要查看实际使用的参数,可以使用查询
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE
然后注意,实际的参数值显示为绑定参数…:
2018-08-07 14:14:36.079 DEBUG 44804 --- [ main] org.hibernate.SQL : select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.joining_date as joining_3_0_, employee0_.name as name4_0_ from employee employee0_ where employee0_.joining_date=?
2018-08-07 14:14:36.079 TRACE 44804 --- [ main] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [TIMESTAMP] - [Tue Aug 07 00:00:00 SGT 2018]
在Spring引导中,我们可以使用两种方法记录SQL语句:
1:使用记录仪
2:标准方法
为日志记录器
您应该将这一行添加到应用程序中。属性文件:
logging.level.org.hibernate.SQL=DEBUG
标准方法
你应该在应用程序中添加这些行。属性文件:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true