在Hibernate中是否有可能用真实值而不是问号打印生成的SQL查询?

如果无法使用Hibernate API,您会建议如何使用实际值打印查询?


当前回答

将以下内容添加到log4j或logback配置中:

org.hibernate.sql=DEBUG
org.hibernate.type.descriptor.sql.BasicBinder=TRACE

其他回答

您需要配置如下:

# Hibernate logging options (INFO only shows startup messages)
log4j.logger.org.hibernate=INFO

# Log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace

MySQL JDBC驱动程序已经提供了一个方便的特性来满足这个需求。您必须至少拥有大于或等于5.1.6的JAR版本(例如mysql-connect-jar-5.1.6.jar)。

配置jdbc。添加日志记录器和自定义日志记录器的Url: jdbc.url = jdbc: mysql: / /主持人:港口/ your_db ?记录器= com.mysql.jdbc.log.Slf4JLogger&profileSQL = true&profilerEventHandler = com.xxx.CustomLoggingProfilerEventHandler

它使用slf4j日志记录,如果你的默认日志记录是log4j,你必须添加slf4j-api和slf4j-log4j12作为依赖项来使用slf4j日志记录:

Write your custom logging code: package com.xxx; import java.sql.SQLException; import java.util.Properties; import com.mysql.jdbc.Connection; import com.mysql.jdbc.log.Log; public class CustomLoggingProfilerEventHandler implements ProfilerEventHandler { private Log log; public LoggingProfilerEventHandler() { } public void consumeEvent(ProfilerEvent evt) { /** * you can only print the sql as his.log.logInfo(evt.getMessage()) * you can adjust your sql print log level with: DEBUG,INFO * you can also handle the message to meet your requirement */ this.log.logInfo(evt); } public void destroy() { this.log = null; } public void init(Connection conn, Properties props) throws SQLException { this.log = conn.getLog(); } }

我喜欢log4j:

log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.engine.query=trace
log4j.logger.org.hibernate.type=trace
log4j.logger.org.hibernate.jdbc=trace
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=error 
log4j.logger.org.hibernate.type.CollectionType=error 

下面是对我有用的,在log4j.file中设置下面的属性:

log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Hibernate属性设置:

hibernate.show_sql=true

如果您使用Spring Boot 3和/或Hibernate 6,以下配置将显示参数值:

# basic log level for all messages
logging.level.org.hibernate=info
# SQL statements and parameters
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.orm.jdbc.bind=trace
# Statistics and slow queries
logging.level.org.hibernate.stat=debug
logging.level.org.hibernate.SQL_SLOW=info
# 2nd Level Cache
logging.level.org.hibernate.cache=debug