技术分享 HIBERNATE 查看内容

hibernate.properties与hibernate.cfg.xml区别

老高 | 发布于 2015-07-16 09:28| 浏览()| 评论() | 收藏() | 点赞() | 打印

摘要: Hibernate的数据库连接信息是从配置文件中加载的。Hibernate的配置文件有两种形式:一种是XML格式的文件,一种是properties属性文件。

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配置文件的相同的属性。


发表评论(对文章涉及的知识点还有疑问,可以在这里留言,老高看到后会及时回复的。)

表情