在上次的博文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配置文件的相同的属性。
本次博文我们暂时先介绍到这里,下次我们讲一下Hibernate中的映射文件,涉及的内容比较多,我们分几次讲解,谢谢关注!