Hibernate(三)Hibernate 配置文件

时间:2021-04-19 16:07:18

在上次的博文Hibernate(二)Hibernate实例我们已经通过一个实例的演示对Hibernate 的基本使用有了一个简单的认识,这里我们在此简单回顾一下Hibernate框架的使用步骤。

Hibernate 框架的使用步骤:

1、创建Hibernate的配置文件

2、创建持久化类,即其实例需要保存到数据库中 的类

3、创建对象-关系映射文件

4、通过Hibernate API编写访问数据库的代码

Hibernate配 置文件

本此博文,我们重点讲解一下Hibernate的配置文件。Hibernate配置文件从形式来讲有两种主 要的格式:一种是Java属性文件,即*.properties,这种配置格式主要定义连接各种数据库需要的参数;还有 一种是XML格式的文件,这种文档除了可以定义连接各种数据库需要的参数,还可以定义程序中用的映射文件 。所以一般情况下使用XML格式的配置文档。
properties形式的配置文件

properties形式的配 置文件默认文件名是hibernate.properties,一个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

XML格式的配置文件

XML格式的配置文件的默认文件名为 hibernate.cfg.xml,一个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>
<!--数据库驱动-->
<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>
<!--显示执行的SQL语句-->
<property name="hibernate.show_sql">true</property> <!--映射文件 -->
<mapping resource="com/zs/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

properties形式的配置文件和XML格式的配置文件可以同时 使用。当同时使用两种类型的配置文件时,XML配置文件中的设置会覆盖properties配置文件的相同的属性。