比如在刪除一條在數據庫操作的時候 我們一般是類似是這樣使用:
this.getHibernateTemplate().delete("from Information where INFOID='"+infoid.trim()+"'");
然而具體在spring內部是怎么操作的呢?
delete()----->excecute()----->執行回調方法HibernateCallback .doInHibernate()。
下面來讓我們來直接看一下spring的源代碼。
//hibernate回調接口
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() {//定義回調實現
public Object doInHibernate(Session session) throws HibernateException {
checkWriteOperationAllowed(session);
return new Integer(session.delete(queryString));//此處有hibernate的實現操作
}
});
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);//此處調用hibernatecallback回調接口即hibernate的實現
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());
}
}
//。。。。。。。。。。。。。。
//其他操作類似
}