首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 進階(三):兩大配置文件詳解與最佳實踐

     編輯:Java 相關知識

Hibernate 使用四步驟回顧

  1. 創建配置文件
  2. 創建持久化類
  3. 創建映射文件
  4. 通過 Hibernate API 訪問數據庫

兩種配置文件格式

1. Properties 格式

默認文件名: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

2. XML 格式(推薦)

默認文件名: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_classJDBC 驅動類com.mysql.jdbc.Driver
connection.urlJDBC 連接串jdbc:mysql://host:3306/db
connection.username數據庫用戶名root
connection.password數據庫密碼123456
dialectSQL 方言MySQLDialect, OracleDialect
show_sql控制台打印 SQLtrue/false
hbm2ddl.auto自動建表策略create, update, validate
current_session_context_classSession 上下文管理thread, managed

下一章預告

將詳細講解映射文件,內容較多將分多篇講解,敬請關注!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved