Hibernate 配置檔支援 hibernate.properties 與 hibernate.cfg.xml 兩種格式,後者較便利 (映射檔可直接在 XML 宣告)。本文系統整理所有核心配置項,重點揭秘 fetch_size、batch_size 等決定效能生死的關鍵參數。
Hibernate 發布包 src/ 目錄下含 hibernate.properties 範本,修改即用。
hibernate.query.substitutions true 1, false 0, yes 'Y', no 'N'
HQL/標準布林值映射至資料庫實際值 (Oracle 無 boolean,用 1/0 或 Y/N),讓代碼更直觀。
hibernate.dialect net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class com.mysql.jdbc.Driver
hibernate.connection.url jdbc:mysql://host/db
hibernate.connection.username root
hibernate.connection.password xxx
hibernate.connection.pool_size 1
hibernate.statement_cache.size 25
警告: 內建連線池極簡陋,**生產環境嚴禁使用**。優先順序:App Server DataSource > DBCP/Proxool > 內建池。
hibernate.connection.provider_class net.sf.hibernate.connection.DBCPConnectionProvider
# 另需 DBCP 專屬配置 (maxActive, maxIdle 等)
hibernate.dialect net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.datasource mypool # JNDI 名稱
hibernate.connection.provider_class net.sf.hibernate.connection.DatasourceConnectionProvider
其他連線參數由 App Server 管理,無需重複配置。
hibernate.jndi.class weblogic.jndi.WLInitialContextFactory
hibernate.jndi.url t3://servername:7001/
# JTA 交易 (EJB 環境)
hibernate.transaction.factory_class net.sf.hibernate.transaction.JTATransactionFactory
hibernate.show_sql false # 開發階段建議 true
輸出 Hibernate 發送給資料庫的實際 SQL,快速定位問題。
# hibernate.connection.isolation 4 # 視資料庫支援而定,通常不用動
hibernate.jdbc.fetch_size 50
fetch_size=10 需 1000 次網路往返;設 50 只要 200 次hibernate.jdbc.batch_size 25
# hibernate.jdbc.use_scrollable_resultset true # 分頁相關,預設即可
# hibernate.cglib.use_reflection_optimizer false # 預設開啟
show_sql=true;生產用 App Server DataSource + show_sql=falsefetch_size=50、batch_size=30~50掌握這些配置,特別是 fetch_size 與 batch_size,是 Hibernate 專案從「跑得動」到「跑得快」的分水嶺。