Hibernate的資料庫連接資訊是從設定檔中載入的。
Hibernate的設定檔有兩種形式:一種是XML格式的檔案,一種是properties屬性檔案。
一)hibernate.cfg.xml
XML格式的設定檔中,除了基本的Hibernate配置資訊,還可以指定具體的持久化類的對應檔,這可以避免將持久化類的設定檔寫入程式碼在程式中。XML格式的設定檔的預設檔案名稱為hibernate.cfg.xml。位置:src/hibernate.cfg.xml。
樣本如下所示:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--顯示執行的SQL語句-->
<property name="show_sql">true</property>
<!--連接字串-->
<property name="connection.url">jdbc:mysql://localhost:3306/STU</property>
<!--串連資料庫的使用者名稱-->
<property name="connection.username">root</property>
<!--資料庫使用者密碼-->
<property name="connection.password">root</property>
<!--資料庫驅動-->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!--選擇使用的方言-->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--對應檔 -->
<mapping resource="com/stuman/domain/Admin.hbm.xml" />
<!--對應檔-->
<mapping resource="com/stuman/domain/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
二)hibernate.properties
properties形式的設定檔預設檔案名稱是hibernate.properties,在設定檔中包含了一系列屬性的配置,Hibernate將根據這些屬性來串連資料庫。位置:src/hibernate.properties。
設定檔內容如下所示:
#指定資料庫使用的驅動類
hibernate.connection.driver_class = com.mysql.jdbc.Driver r
#指定資料庫連接串
hibernate.connection.url = jdbc:mysql://localhost:3306/db
#指定資料庫連接的使用者名稱
hibernate.connection.username = user
#指定資料庫連接的密碼
hibernate.connection.password = password
#指定資料庫使用的方言
hibernate.dialect = net.sf.hibernate.dialect.MySQLDialect
#指定是否列印SQL語句
hibernate.show_sql=true
三)
properties形式的設定檔和XML格式的設定檔可以同時使用。當同時使用兩種類型的設定檔時,XML設定檔中的設定會覆蓋properties設定檔的相同的屬性。
SOURCE: http://hanshuo528.bokee.com/viewdiary.23028288.html