您的位置:首页 > 其它

Hibernate的两种配置方法

2007-12-21 21:13 405 查看
1、 hibernate的配置文件:hibernate可以使用properties文件配置也可以使用xml文件配置,用properties进行配置时(例子如下):
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进行配置时(例子如下):
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:两种配置方式各有什么优点?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: