Hibernate的两种配置方法

1、 hibernate的配置文件:hibernate可以使用properties文件配置也可以使用xml文件配置,用properties进行配置时(例子如下):
1)hibernate.properties
hibernate.connection.url=jdbc:mysql://localhost:3306/test
hibernate.connection.username=root
hibernate.connection.password=root
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
使用propertie文件配置时,只能在properties文件中配置基本信息,如果要添加映射文件信息,得使用硬编码:
Configuration cf = new Configuration().addResource(“映射文件的地址”);
在使用new Configuration()时,Hibernate默认会在root of classpath下查找hibernate.properties文件。
使用xml进行配置时(例子如下):
2)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>
   <property name=”connection.url”>jdbc:mysql://localhost:3306/test</property>
   <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
   <property name=”connection.username”>root</property>
   <property name=”connection.password”>root</property>
   <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
   <property name=”show_sql”>true</property>
   <mapping resource=”manning/ch02/hello/User.hbm.xml”/>
</session-factory>
</hibernate-configuration>
加载配置文件:
Configuration cf = new Configuration().configure();在使用configure()时,Hibernate默认会加载在root of classpath下的hibernate.cfg.xml文件,如果想修改xml配置文件的位置,可以在configure(“配置文件的地址”);
比较:
1.        加载时机的不同:在使用Configuration cf = new Configuration()时加载properties配置文件,而在使用new Configuration().configure()时加载xml配置文件,因此如果使用properties配置文件时无需添加.configure().
2.        优先级不同:如果同时使用properties配置文件和xml配置文件,且配置项相同时,xml配置文件会覆盖掉properties配置文件的内容。
问题1:如何修改properties配置文件的位置?
问题2:两种配置方式各有什么优点?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值