JDBC连接
通常你希望SessionFactory来为你创建和缓存(pool)JDBC连接. 如果你采用这种方式, 只需要如下例所示那样,打开一个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连接 :
表 3.1. Hibernate JDBC属性
属性名 | 用途 |
---|---|
hibernate.connection.driver_class | jdbc驱动类 |
hibernate.connection.url | jdbc URL |
hibernate.connection.username | 数据库用户 |
hibernate.connection.password | 数据库用户密码 |
hibernate.connection.pool_size | 连接池容量上限数目 |
但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处获得连接,你至少需要设置下列属性中的一个:
表 3.2. Hibernate数据源属性
属性名 | 用途 |
---|---|
hibernate.connection.datasource | 数据源JNDI名字 |
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, 你可以选择一个自定义的实现.