hibernate.properties與hibernate.cfg.xml區別

Hibernate的數據庫連接信息是從配置文件中加載的。

Hibernate的配置文件有兩種形式:一種是XML格式的文件,一種是properties屬性文件。

一、hibernate.cfg.xml

XML格式的配置文件中,除了基本的Hibernate配置信息,還可以指定具體的持久化類的映射文件,這可以避免將持久化類的配置文件硬編碼在程序中。XML格式的配置文件的默認文件名爲hibernate.cfg.xml。位置:src/hibernate.cfg.xml。

示例如下所示:

<span style="font-family:Microsoft YaHei;font-size:12px;"><?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>
		<!--數據庫驅動 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</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="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!--顯示執行的SQL語句 -->
		<property name="show_sql">true</property>
		<!--映射文件 -->
		<mapping resource="com/stuman/domain/Admin.hbm.xml" />
		<mapping resource="com/stuman/domain/Student.hbm.xml" />
	</session-factory>
</hibernate-configuration></span>

二、hibernate.properties

properties形式的配置文件默認文件名是hibernate.properties,在配置文件中包含了一系列屬性的配置,Hibernate將根據這些屬性來連接數據庫。位置:src/hibernate.properties。

配置文件內容如下所示:

<span style="font-family:Microsoft YaHei;font-size:12px;">#指定數據庫使用的驅動類
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
</span>

三、總結

properties形式的配置文件和XML格式的配置文件可以同時使用。當同時使用兩種類型的配置文件時,XML配置文件中的設置會覆蓋properties配置文件的相同的屬性。

文章轉自 : hibernate.properties與hibernate.cfg.xml區別


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章