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

  • 相关阅读:
    聚合支付里各扫码支付的返回报文样例
    短信平台接口安全控制
    「美团外卖APP签约快捷支付」流程体验
    多模块项目提示“Module ** must not contain source root **. The root already belongs to module **”的解决办法
    比较两种方式的form请求提交
    Linux screen命令和系统日志
    Linux 守护进程
    Linux 进程的通信方式与信号:kill命令
    Linux 进程的控制与进程之间的关系
    Linux 使用ps和top命令查看进程
  • 原文地址:https://www.cnblogs.com/51cto/p/1420401.html
Copyright © 2011-2022 走看看