ITEEDU

Hibernate Gossip: 配置文件

Hibernate可以使用XML档案或properties档案来配置SessionFactory,预设的配置文件名称为 hibernate.cfg.xml或hibernate.properties,XML提供较好的结构与配置方式,Hibernate建议使用XML档 案进行配置。

前几个主题中所示范的为使用XML文件的方式,一个XML文件的例子如下:
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>
<!-- SQL方言,这边设定的是MySQL -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- JDBC驱动程序 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- JDBC URL -->
<property name="connection.url">jdbc:mysql://localhost/demo</property>
<!-- 数据库使用者 -->
<property name="connection.username">caterpillar</property>
<!-- 数据库密码 -->
<property name="connection.password">123456</property>

<!-- 对象与数据库表格映像文件 -->
<mapping resource="onlyfun/caterpillar/User.hbm.xml"/>

</session-factory>

</hibernate-configuration>

使用XML文件进行配置时,可以在当中指定对象与数据库表格的映像文件位置,XML配置文件的位置必须在Classpath下,使用下面的方式来读入XML文件以配置Hibernate:

      Configuration config = new Configuration().configure();
Configuration的实例管理Hibernate的配置讯息,通常用于建立SessionFactory,例如:

SessionFactory sessionFactory = config.buildSessionFactory();
SessionFactory一旦建立,就被赋予当时Configuration的配置讯息,之后您改变Configuration并不会影响已建立的 SessionFactory实例,如果对Configuration改动后,则要建立一个新的SessionFactory实例,新的实例中会包括新的 配置讯息。

SessionFactory中包括了数据库配置及映像关系,它的建立相当复杂,所以使用时需考虑到重用已建立的SessionFactory实例,SessionFactory是被设计为「执行绪安全的」(Thread-safe)。

预设的XML配置文件名称是hibernate.cfg.xml,您也可以自行指定档案,例如:
Configuration config = new Configuration().configure("db.cfg.xml");
SessionFactory sf = config.buildSessionFactory();
除了使用XML文件进行配置,您也可以使用属性档案进行配置,文件名称是hibernate.properties,一个例子如下:
hibernate.properties
hibernate.show_sql = true 
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost/demo
hibernate.connection.username = caterpillar
hibernate.connection.password = 123456
hibernate.properties的位置必须在Classpath下,由于properties档案中不包括映像文件的名称,为了要取得对象至数据库表格的映像文件,您必须在程序中如下加载:
 Configuration cfg = new Configuration()
    .addClass(onlyfun.caterpillar.User.class)
    .addClass(onlyfun.caterpillar.Item.class);
第一个addClass()加入位于Classpath根目录下的User.hbm.xml,第二个addClass()加入Item类别的映像文件,该文件必须位于与User类别同一个目录,也就是onlyfun/caterpillar/Item.hbm.xml。

在Hibernate下载档案中的etc目录下,有hibernate.cfg.xml与hibernate.properties可供设定参考。