Hibernate的配置1

Hibernate的配置
Hibernate被设计适用于许多不同的环境,所以有很多的配置参数。幸运的是大多数都有很好的默认值。而且在Hibernate的发布中在etc/目录下有一个hibernate.properties文件,显示不同的版本。你只需要按照自己的需求来修改并拷贝就可以了
1. 可编程换配置
org.hibernate.cfg.Configuration的一个实例就代表一个数据库的映射。org.hibernate.cfg.Configuration用来创建一个不可变的org.hibernate.SessionFactory

你可以自己实例换一个org.hibernate.cfg.Configuration对象,然后给它指定映射文件,如果这些配置文件在classpath路径下,可以使用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);

org.hibernate.cfg.Configuration还允许你指定一些配置属性,比如
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");


当然你可以通过其他的方法添加properties到hibernate
通过Configuration.setProperties()传递一个java.util.Properties实例到 hibernate
用hibernate.properties配置
在hibernate.cfg.xml中通过propertity元素来配置

org.hibernate.cfg.Configuration只是在启动的时候需要,一旦SessionFactory创建,他就被丢弃了。

2. 如何获得SessionFactory
在所有的mapping文件被hibernate转化之后,程序获得一个Session的工厂。这个工厂被程序的所有线程所共享。
SessionFactory sessionFactory = cfg.buildSessionFactory();


3. JDBC连接
在你可以工作事,需要获得一个JDBC的连接。在Hibernate中获取一个JDBC的连接很简单 通过Session session= sessionFactory.openSession();,但是在你获取一个连接前,你需要传递给Hibernate一些JDBC的属性。Hibernate所有的属性都是定义在org.hibernate.cfg.Environment中 比如一些重要的JDBC属性
Property name Purpose
hibernate.connection.driver_class JDBC driver class
hibernate.connection.url JDBC URL
hibernate.connection.username database user
hibernate.connection.password database user password
hibernate.connection.pool_size maximum number of pooled connections
Hibernate有一个基本的连接池算法,但是不适合在生产环境中使用。你需要使用一个第三方的稳定的连接池。比如c3p0
C3P0是一个开源的JDBC连接池。包含在在hibernate的发布版本中的lib目录下。Hibernate将会使用org.hibernate.connection.C3P0ConnectionProvider

猜你喜欢

转载自hellogava.iteye.com/blog/1571301
今日推荐