Hibernate打印SQL及附加参数

    今天在项目运行过程中,一直报一个org.hibernate.exception.GenericJDBCException: could not insert 异常,Root Cause是IBM  DB2 ErrorCode=-180,sqlstate=22007,经过Google,发现这个错误的原因是因为Timestamp的格式不规范导致,但是具体是哪一项,却不太清楚,如果能够打印出导致问题的SQL语句,那么对于这类问题的定位就会非常容易了。

      在Hibernate的配置文件hibernate.cfg.xml中有3个设置项跟显示SQL语句相关,他们的值都是boolean值:
    (1)、show_sql:是否显示SQL语句
    (2)、format_sql: 是否格式化输出字符串,增强SQL的可读性
    (3)、use_sql_comments:是否显示注释,用于指示出是什么操作产生了这个SQL语句。
   
     在默认情况下,Hibernate会把SQL语句打印在Console上,因此在开启了上面的设置之后,可以在控制台上看到如下结构的SQL语句:
 /* load collection cc.unmi.test.model.Post.securities */ select
        securities0_.post_id as post1_7_1_,
        security1_.shareclassid as sharecla1_16_0_,
        security1_.company_id as company2_16_0_,
    from
        Post_Security_Relationship securities0_
    inner join
        unmi.securities security1_
            on securities0_.shareclassid=security1_.shareclassid
    where
        securities0_.post_id=?

   可以发现,在控制台上根本看不到,SQL语句对应的参数,一般情况下,Hibernate都会和Log4j配合使用,这样就可以更加灵活的控制hibernate的日志文件输出。在hibernate中,默认的关于SQL语句对应参数的输出级别为TRACE,比默认的Log4j的日志等级DEBUG还要低一等级,因此,为了显示参数,还需手动设置一下log4j的配置,把hibernate下的输出等级改为TRACE:
log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
log4j. loggerorg.hibernate.type.descriptor.sql.BasicExtractor=TRACE 
这样修改之后,打印的SQL语句会变为如下形式:
20:13:40.710 [http-8080-1] DEBUG org.hibernate.SQL -
    /* load collection cc.unmi.test.model.Post.categories */ select
        categories0_.post_id as post1_7_1_,
        elementite1_.id as id3_0_,
    from
        Post_Category_Relationship categories0_
    inner join
        unmi.element_item elementite1_
            on categories0_.category_id=elementite1_.id
    where
        categories0_.post_id=?
20:13:40.710 [http-8080-1] TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [INTEGER] - 10
20:13:40.710 [http-8080-1] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [1002] as column [id3_0_]
20:13:40.710 [http-8080-1] TRACE org.hibernate.type.descriptor.sql.BasicExtractor - found [10] as column [post1_7_1_]

如果还想查看查询中命名参数的值,还需要在log4j的配置文件中加上如下的值:
log4j.logger.org.hibernate.engine.QueryParameters=DEBUG
log4j.logger.org.hibernate.engine.query.HQLQueryPlan=DEBUG
这样修改之后,可以得到如下的结果:
20:13:40.710 [http-8080-1] org.hibernate.engine.query.HQLQueryPlan - find: from User where email = :email
20:13:40.710 [http-8080-1] org.hibernate.engine.QueryParameters - named parameters: {[email protected]}
20:13:40.726 [http-8080-1] org.hibernate.SQL -
    /* named HQL query findUserByEmail */ select
        user0_.id as id0_,
        user0_.email as email0_,
        user0_.enabled as enabled0_,
        user0_.encodedPassword as encodedP8_0_
    from
        User user0_
    where
        user0_.email=?

猜你喜欢

转载自ningandjiao.iteye.com/blog/1604700