首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

Hibernate JDBC联接详解

2012-08-25 
Hibernate JDBC连接详解Hibernate JDBC连接通常你希望SessionFactory来为你创建和缓存(pool)JDBC连接. 如

Hibernate JDBC连接详解

    Hibernate JDBC连接

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

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

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

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

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

    表 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样例文件:

    1. hibernate.connection.driver_class?=?org.postgresql.Driver ?
    2. hibernate.connection.url?=?jdbc:postgresql://localhost/mydatabase ?
    3. hibernate.connection.username?=?myuser?
    4. hibernate.connection.password?=?secret?
    5. hibernate.c3p0.min_size=5?
    6. hibernate.c3p0.max_size=20?
    7. hibernate.c3p0.timeout=1800?
    8. hibernate.c3p0.max_statements=50?
    9. hibernate.dialect?=?org.hibernate.dialect.PostgreSQLDialect?

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

    表 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样例文件:

    1. hibernate.connection.datasource?=?java:/comp/env/jdbc/test ?
    2. hibernate.transaction.factory_class?=?\ ?
    3. ?org.hibernate.transaction.JTATransactionFactory ?
    4. hibernate.transaction.manager_lookup_class?=?\ ?
    5. ????org.hibernate.transaction.JBossTransactionManagerLookup ?
    6. hibernate.dialect?=?org.hibernate.dialect.PostgreSQLDialect?

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

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

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

    ?

热点排行