默認文件名:hibernate.properties
僅能配置數據庫連接參數,無法配置映射文件。
# 數據庫驅動
hibernate.connection.driver_class = com.mysql.jdbc.Driver
# 連接串
hibernate.connection.url = jdbc:mysql://localhost:3306/hibernate_first
# 用戶名/密碼
hibernate.connection.username = user
hibernate.connection.password = password
# 方言
hibernate.dialect = org.hibernate.dialect.MySQLDialect
# 顯示 SQL
hibernate.show_sql=true
默認文件名:hibernate.cfg.xml
除連接參數外,可配置映射文件路徑,功能更完整。
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- 關鍵:映射文件引用 -->
<mapping resource="com/zs/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
若同時存在兩類文件,XML 配置會覆蓋 Properties 同名屬性。建議統一使用 XML,避免混淆。
| 配置項 | 用途 | 常見值 |
|---|---|---|
| connection.driver_class | JDBC 驅動類 | com.mysql.jdbc.Driver |
| connection.url | JDBC 連接串 | jdbc:mysql://host:3306/db |
| connection.username | 數據庫用戶名 | root |
| connection.password | 數據庫密碼 | 123456 |
| dialect | SQL 方言 | MySQLDialect, OracleDialect |
| show_sql | 控制台打印 SQL | true/false |
| hbm2ddl.auto | 自動建表策略 | create, update, validate |
| current_session_context_class | Session 上下文管理 | thread, managed |
將詳細講解映射文件,內容較多將分多篇講解,敬請關注!