Hibernate JDBC 连接

通常你希望org.hibernate.SessionFactory 来为你创建和缓存(pool)JDBC 连接。如果你采用这种方式,只需要如下例所示那样,打开一个 org.hibernate.Session

Session session = sessions.openSession(); // open a new Session

一旦你需要进行数据访问时,就会从连接池(connection pool)获得一个 JDBC 连接。

为了使这种方式工作起来,我们需要向 Hibernate 传递一些 JDBC 连接的属性。所有 Hibernate 属性的名字和语义都在org.hibernate.cfg.Environment 中定义。我们现在将描述 JDBC 连接配置中最重要的设置。

如果你设置如下属性,Hibernate 将使用 java.sql.DriverManager 来获得(和缓存)JDBC 连接:

Hibernate JDBC 属性

属性名 用途
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 自带的连接池算法相当不成熟。它只是为了让你快些上手,并不适合用于产品系统或性能测试中。 出于最佳性能和稳定性考虑你应该使用第三方的连接池。只需要用特定连接池的设置替换 hibernate.connection.pool_size 即可。这将关闭 Hibernate 自带的连接池。例如,你可能会想用 C3P0。

C3P0 是一个随 Hibernate 一同分发的开源的 JDBC 连接池,它位于 lib目录下。 如果你设置了 hibernate.c3p0.* 相关的属性,Hibernate将使用 C3P0ConnectionProvider 来缓存 JDBC 连接。如果你更原意使用 Proxool,请参考发行包中的 hibernate.properties 并到 Hibernate 网站获取更多的信息。

这是一个使用 C3P0 的 hibernate.properties 样例文件:

hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

为了能在应用程序服务器(application server)中使用 Hibernate,应当总是将 Hibernate 配置成从注册在 JNDI 中的Datasource 处获得连接,你至少需要设置下列属性中的一个:

Hibernate 数据源属性

属性名 用途
hibernate.connection.datasource datasource JNDI name
hibernate.jndi.url JNDI 提供者的 URL(可选)
hibernate.jndi.class JNDI InitialContextFactory 类(可选)
hibernate.connection.username 数据库用户(可选)
hibernate.connection.password 数据库密码(可选)

这是一个使用应用程序服务器提供的 JNDI 数据源的 hibernate.properties 样例文件:

hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

从 JNDI 数据源获得的 JDBC 连接将自动参与到应用程序服务器中容器管理的事务(container-managed transactions)中去。

任何连接(connection)属性的属性名都要以 "hibernate.connnection" 开头。例如,你可能会使用hibernate.connection.charSet 来指定 charSet 连接属性。

通过实现 org.hibernate.connection.ConnectionProvider 接口,你可以定义属于你自己的获得JDBC连接的插件策略。通过设置hibernate.connection.provider_class,你可以选择一个自定义的实现。


posted @ 2012-04-19 19:04  Springside4  阅读(233)  评论(0编辑  收藏  举报