zoukankan      html  css  js  c++  java
  • Spring JDBCTemplate与Hiberante混用

          一开始在项目中使用的是JDBCTemplate,为了提高开发效率决定采用Hibernate,但是发现Hibernate在做批量操作时,效率不是很理想。所以现在采用JDBCTemplate和Hibernate混用,JDBCTemplate和Hibernate混用是可以的,有几个注意事项.

    1.如果采用JDBCTemplate的部分只涉及到查询,则可以使用Hibernate的应用缓存,即二级缓存.

    2.如果采用JDBCTemplate的部分涉及到对数据库的更新操作,即增,删,改.则不能开启Hibernate的二级缓存,如果系统有缓存的需要,我觉得可以自己在逻辑层实现缓存.Java的缓存方案还是很多的.

    3.在使用Spring做为容器的系统中,混用JDBCTemplate和Hibernate,事务管理请统一使用HibernateTransactionManager,前提是JDBCTemplate和Hibernate共用一个DataSource.

    在HibernateTransactionManager的类说明中有一段原话

    This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access Hibernate and services which use plain JDBC (without being aware of Hibernate)! Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy).

    从代码的角度上看也是可以混用的.事务可以统一管理。HibernateTransactionManager的doBegin方法中有这么一段代码

     1    // add the Hibernate transaction to the session holder
     2    txObject.getSessionHolder().setTransaction(session.beginTransaction());
     3    // register transaction timeout
     4    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT)
     5 
     6    {
     7       txObject.getSessionHolder().setTimeoutInSeconds(definition.getTimeout());
     8    }
     9    // bind the session holder to the thread
    10    if (txObject.isNewSessionHolder())
    11    {
    12        TransactionSynchronizationManager.bindResource(this.sessionFactory,      txObject.getSessionHolder());
    13    }
    14    // register the Hibernate Session's JDBC Connection for the DataSource, if set
    15    if (this.dataSource != null)
    16 
    17    {
    18      ConnectionHolder conHolder = new ConnectionHolder(session.connection());
    19      if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT)
    20      {
    21           conHolder.setTimeoutInSeconds(definition.getTimeout());
    22      }
    23     TransactionSynchronizationManager.bindResource(this.dataSource, conHolder);
    24    }
    25 
    26 

    注意这一注释 register the Hibernate Session's JDBC Connection for the DataSource, if set

  • 相关阅读:
    初识 MyBatis
    基于模板匹配的车牌识别
    完整java开发中JDBC连接数据库代码和步骤
    MyBatis 动态SQL
    最大子序列和问题
    二分搜索,欧几里德算法
    链表单链表
    UVA 12293 Box Game
    hdu 4565 so easy
    Bootstrap Table的使用 Cryst
  • 原文地址:https://www.cnblogs.com/51cto/p/1420401.html
Copyright © 2011-2022 走看看