Hibernate入门之配置文件(3)

Hibernate可以使用XML或属性档案来配置SessionFactory,预设的配置文件名称为hibernate.cfg.xml或hibernate.properties。 
 上一个主题中所示范的为使用XML文件的方式,一个XML文件的例子如下: 

hibernate.cfg.xml

 

<?xml version=‘1.0‘ encoding=‘big5‘?> 
<!DOCTYPE hibernate-configuration 
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" 
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"> 

<hibernate-configuration> 

<session-factory> 

<!-- 显示实际操作数据库时的SQL --> 
<property name="show_sql">true</property> 
<!-- SQL方言,这边设定的是MySQL --> 
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property> 
<!-- JDBC驱动程序 --> 
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
<!-- JDBC URL --> 
<property name="connection.url">jdbc:mysql://localhost/HibernateTest</property> 
<!-- 数据库使用者 --> 
<property name="connection.username">caterpillar</property> 
<!-- 数据库密码 --> 
<property name="connection.password">123456</property> 

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

</session-factory> 

</hibernate-configuration> 

 使用XML文件进行配置时,可以在当中指定对象与数据库表格的映像文件位置,XML配置文件的位置必须在CLASSPATH的设定中,例如单机执行时主程序的位置,或是Web程序的WEB-INF/classes中,我们使用下面的方式来读入XML文件以配置Hibernate: 

 

SessionFactory sf = new Configuration().configure().buildSessionFactory(); 

 Configuration表示Java对象与数据库表格映像的集合,并用于之后建立SessionFactory,之后Configuration就不再有作用。预设的XML文件名称是hibernate.cfg.xml,您也可以指定文件的名称,例如:

SessionFactory sf = new Configuration() 
.configure("db.cfg.xml") 
.buildSessionFactory(); 

 除了使用XML文件进行配置,我们也可以使用属性档案进行配置,文件名称是hibernate.properties,一个例子如下:

首先新建一个名为hibernate.propertites的文件,特别要注意后缀

hibernate.properties文件内容如下:

hibernate.show_sql = true 
hibernate.dialect = net.sf.hibernate.dialect.MySQLDialect 
hibernate.connection.driver_class = com.mysql.jdbc.Driver 
hibernate.connection.url = jdbc:mysql://localhost/HibernateTest 
hibernate.connection.username = caterpillar 
hibernate.connection.password = 123456 

 hibernate.properties的位置必须在CLASSPATH的设定中,例如单机执行时主程序的位置,或是Web程序的WEB-INF/classes中,而为了要取得对象至数据库表格的映像文件,我们必须在程序中如下加载: 

Configuration cfg = new Configuration() 
.addClass(onlyfun.caterpillar.User.class) 
.addClass(onlyfun.caterpillar.Item.class); 

 这么一来,程序会自动加载onlyfun/caterpillar/User.hbm.xml与onlyfun/caterpillar/Item.hbm.xml,完成Hibernate配置之后,我们可以如下取得SessionFactory:

SessionFactory sessions = cfg.buildSessionFactory(); 

 其它更多有关Hibernate配置的细节,您可以查看Hibernate参考手册。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值