一开始在项目中使用的是JDBCTemplate,为了提高开发效率决定采用Hibernate,但是发现Hibernate在做批量操作时,效率不是很理想。所以现在采用JDBCTemplate和Hibernate混用,JDBCTemplate和Hibernate混用是可以的,有几个注意事项.
1.如果采用JDBCTemplate的部分只涉及到查询,则可以使用Hibernate的应用缓存,即二级缓存.
2.如果采用JDBCTemplate的部分涉及到对数据库的更新操作,即增,删,改.则不能开启Hibernate的二级缓存,如果系统有缓存的需要,我觉得可以自己在逻辑层实现缓存.Java的缓存方案还是很多的.
3.在使用Spring做为容器的系统中,混用JDBCTemplate和Hibernate,事务管理请统一使用HibernateTransactionMana
在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 DataSourceTransactionMan
从代码的角度上看也是可以混用的.事务可以统一管理。HibernateTransactionMana
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