今天在項目運行過程當中,一直報一個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語句: 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語句會變爲以下形式: post
- 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
這樣修改以後,能夠獲得以下的結果: spa
- 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=fantasia@sina.com}
- 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=?