Spring 對(duì) hibernate 的集成(使用回調(diào)callback)
Posted on 2007-05-28 15:27 change 閱讀(1560) 評(píng)論(0) 編輯 收藏比如在刪除一條在數(shù)據(jù)庫(kù)操作的時(shí)候 我們一般是類似是這樣使用:
this.getHibernateTemplate().delete("from Information where INFOID='"+infoid.trim()+"'");
然而具體在spring內(nèi)部是怎么操作的呢?
delete()----->excecute()----->執(zhí)行回調(diào)方法HibernateCallback .doInHibernate()。
下面來(lái)讓我們來(lái)直接看一下spring的源代碼。
//hibernate回調(diào)接口
public interface HibernateCallback {
Object doInHibernate(Session session) throws HibernateException, SQLException;
}
//
package org.springframework.orm.hibernate;
public class HibernateTemplate extends HibernateAccessor implements HibernateOperations {
//。。。。。。。。。。。。。。。。
public int delete(final String queryString) throws DataAccessException {
Integer deleteCount = (Integer) execute(new HibernateCallback() {//定義回調(diào)實(shí)現(xiàn)
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return new Integer(session.delete(queryString));//此處有hibernate的實(shí)現(xiàn)操作
}
});
return deleteCount.intValue();
}
public Object execute(HibernateCallback action) throws DataAccessException {
Session session = (!isAllowCreate() ? SessionFactoryUtils.getSession(getSessionFactory(), false) :
SessionFactoryUtils.getSession(getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator()));
boolean existingTransaction = TransactionSynchronizationManager.hasResource(getSessionFactory());
if (!existingTransaction && getFlushMode() == FLUSH_NEVER) {
session.setFlushMode(FlushMode.NEVER);
}
try {
Object result = action.doInHibernate(session);//此處調(diào)用hibernatecallback回調(diào)接口即hibernate的實(shí)現(xiàn)
flushIfNecessary(session, existingTransaction);
return result;
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
catch (SQLException ex) {
throw convertJdbcAccessException(ex);
}
catch (RuntimeException ex) {
// callback code threw application exception
throw ex;
}
finally {
SessionFactoryUtils.closeSessionIfNecessary(session, getSessionFactory());
}
}
//。。。。。。。。。。。。。。
//其他操作類似
}