Hibernate show sql is equal to Stdout

2019-08-16 08:45发布

问题:

I declared <property name="show_sql">true</property> in hibernate. I read stdout issues in this link. Stdout will consume more memory. So How show_sql functionality will working?. Because of I have seen in server log stdout sql query.

13:06:53,323 INFO  [stdout] (http-/172.29.250.43:8080-7) Hibernate: select sampledata0_.idsample as idsample4_10_1_, sampledata0_.id as id1_9_1_, sampledata0_.id as id1_9_0_, sampledata0_.idsample as idsample4_9_0_, sampledata0_.sname as sname2_9_0_, sampledata0_.svalue as svalue3_9_0_ from sample_meta_data sampledata0_ where sampledata0_.idsample=?
13:06:53,324 INFO  [stdout] (http-/172.29.250.43:8080-7) Hibernate: select sampledata0_.idsample as idsample4_10_1_, sampledata0_.id as id1_9_1_, sampledata0_.id as id1_9_0_, sampledata0_.idsample as idsample4_9_0_, sampledata0_.sname as sname2_9_0_, sampledata0_.svalue as svalue3_9_0_ from sample_meta_data sampledata0_ where sampledata0_.idsample=?

Internally hibernate suppose to use System.out.println. Then Will it consume more memory? How format_sql and show_sql working internally?

回答1:

Setting true for show_sql and format_sql will not consume more memory but they will write the SQL statements to console so it is time consuming.

From documentation:

Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.

e.g. true | false

So when you set the property show_sql to true then hibernate prints the SQL statement to console using below method:

Hibernate uses below method for displaying the SQL statement from SQLStatementLogger class that it uses internally.

/**
 * Log a SQL statement string.
 *
 * @param statement The SQL statement.
 * @param style The requested formatting style.
 */
public void logStatement(String statement, FormatStyle style) {
    if ( log.isDebugEnabled() || logToStdout ) {
        style = determineActualStyle( style );
        statement = style.getFormatter().format( statement );
    }
    log.debug( statement );
    if ( logToStdout ) {
        System.out.println( "Hibernate: " + statement );
    }
}

In the above method if the format_sql is set to true then the SQL statement will be formatted or else the formatting style will not be applied.

Now if the LOG level is set to DEBUG then the SQL statement is written to log file. If you set the show_sql to true then it prints the message to console. As mentioned in the link provided in your question, using System.out.println is more time consuming compared to printing data to log file.

In general when the application is in production then the log level will not be set to DEBUG as writing messages to log files takes some time.



回答2:

When show_sql is ture, statements will be printed into system.out; and if you want to statements printed into the file log4j set, you should set the level of log4j.logger.org.hibernate.SQL to DEBUG