由于Hibernate是为了能在各种不同环境下工作而设计的, 因此存在着大量的配置参数. 幸运的是多数配置参数都 有比较直观的默认值, 并有随Hibernate一同分发的配置样例hibernate.properties
(位于etc/
)来展示各种配置选项. 所需做的仅仅是将这个样例文件复制到类路径 (classpath)下并做一些自定义的修改.
An instance of org.hibernate.cfg.Configuration
represents an entire set of mappings of an application's Java types to an SQL database. The org.hibernate.cfg.Configuration
is used to build an (immutable) org.hibernate.SessionFactory
. The mappings are compiled from various XML mapping files.
You may obtain a org.hibernate.cfg.Configuration
instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use
addResource()
:
Configuration cfg = new Configuration() .addResource("Item.hbm.xml") .addResource("Bid.hbm.xml");
一个替代方法(有时是更好的选择)是,指定被映射的类,让Hibernate帮你寻找映射定义文件:
Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class);
Then Hibernate will look for mapping files named /org/hibernate/auction/Item.hbm.xml
and /org/hibernate/auction/Bid.hbm.xml
in the classpath. This approach eliminates any hardcoded filenames.
A org.hibernate.cfg.Configuration
also allows you to specify configuration properties:
Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect") .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test") .setProperty("hibernate.order_updates", "true");
当然这不是唯一的传递Hibernate配置属性的方式, 其他可选方式还包括:
Pass an instance of java.util.Properties
to Configuration.setProperties()
.
Place a file named hibernate.properties
in a root directory of the classpath.
通过java -Dproperty=value
来设置系统 (System
)属性.
在hibernate.cfg.xml
中加入元素 <property>
(稍后讨论).
hibernate.properties
is the easiest approach if you want to get started quickly.
The org.hibernate.cfg.Configuration
is intended as a startup-time object, to be discarded once a SessionFactory
is created.