参考 dongnan591172113的博文改改的,算半个原创吧:
原地址 http://blog.csdn.net/dongnan591172113/article/details/8052868
import java.sql.SQLException; import java.sql.Savepoint; import java.util.concurrent.atomic.AtomicInteger; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionSystemException; import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.ResourceTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.support.DatabaseConnection; import com.mysql.jdbc.Connection; public class ORMLiteTransactionManager extends org.springframework.transaction.support.AbstractPlatformTransactionManager implements ResourceTransactionManager, BeanFactoryAware, InitializingBean{ private static final long serialVersionUID = -6494056879630902365L; private ConnectionSource connectionSource; private static AtomicInteger savePointCounter = new AtomicInteger(); private static final String SAVE_POINT_PREFIX = "ORMLITE_TR"; public void setConnectionSource(ConnectionSource connectionSource) { this.connectionSource = connectionSource; } public ConnectionSource getConnectionSource() { return connectionSource; } public ORMLiteTransactionManager(){ setNestedTransactionAllowed(true); } public ORMLiteTransactionManager(ConnectionSource connectionSource) { this(); setConnectionSource(connectionSource); afterPropertiesSet(); } @Override public Object getResourceFactory() { return getConnectionSource(); } @Override protected Object doGetTransaction() throws TransactionException { logger.debug("start transaction"); ConnectionSourceTransactionObject txObject = new ConnectionSourceTransactionObject(); txObject.setSavepointAllowed(isNestedTransactionAllowed()); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.connectionSource); txObject.setConnectionHolder(conHolder, false); return txObject; } protected boolean isExistingTransaction(Object transaction) { ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) transaction; //根据存放数据库连接的ConnectionHolder的isTransactionActive属性来判断 return (txObject.getConnectionHolder() != null && txObject.getConnectionHolder().isTransactionActive()); } @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) transaction; DatabaseConnection con = null; try { //如果数据源事务对象的ConnectionHolder为null或者是事务同步的 if (txObject.getConnectionHolder() == null || txObject.getConnectionHolder().isSynchronizedWithTransaction()) { //获取当前数据源的数据库连接 DatabaseConnection newCon = (definition.isReadOnly() ? connectionSource.getReadOnlyConnection() : connectionSource.getReadWriteConnection()); if (logger.isDebugEnabled()) { logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction"); } //为数据源事务对象设置ConnectionHolder txObject.setConnectionHolder(new ConnectionHolder(newCon, connectionSource.getDatabaseType().isNestedSavePointsSupported()), true); } //设置数据源事务对象的事务同步 txObject.getConnectionHolder().setSynchronizedWithTransaction(true); //获取数据源事务对象的数据库连接 con = txObject.getConnectionHolder().getConnection(); //如果数据库连接设置了自动事务提交属性,则关闭自动提交 if (con.isAutoCommit()) { //保存数据库连接设置的自动连接到数据源事务对象中 txObject.setMustRestoreAutoCommit(true); if (logger.isDebugEnabled()) { logger.debug("Switching JDBC Connection [" + con + "] to manual commit"); } //设置数据库连接自动事务提交属性为false,即禁止自动事务提交 con.setAutoCommit(false); } //激活当前数据源事务对象的事务配置 txObject.getConnectionHolder().setTransactionActive(true); //获取事务配置的超时时长 int timeout = determineTimeout(definition); //如果事务配置的超时时长不等于事务的默认超时时长 if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) { //数据源事务对象设置超时时长 txObject.getConnectionHolder().setTimeoutInSeconds(timeout); } //把当前数据库Connection和线程绑定 if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.bindResource(getConnectionSource(), txObject.getConnectionHolder()); } } catch (Exception ex) { try { connectionSource.releaseConnection(con); } catch (SQLException e) { throw new CannotCreateTransactionException(e.getMessage(), ex); } throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex); } } // 事务挂起 @Override protected Object doSuspend(Object transaction) { //获取事务对象 ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) transaction; //将事务对象中的ConnectionHolders设置为null txObject.setConnectionHolder(null); ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.unbindResource(this.connectionSource); //解除事务对象和当前线程的绑定 return conHolder; } // 事务恢复 protected void doResume(Object transaction, Object suspendedResources) { // 获取已暂停事务的ConnectionHolder ConnectionHolder conHolder = (ConnectionHolder) suspendedResources; // 重新将事务对象和当前线程绑定 TransactionSynchronizationManager.bindResource(this.connectionSource, conHolder); } @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { //获取事务对象 ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) status.getTransaction(); //通过事务对象获取数据库连接 DatabaseConnection con = txObject.getConnectionHolder().getConnection(); if (status.isDebug()) { logger.debug("Committing JDBC transaction on Connection [" + con + "]"); } try { //使用数据库连接手动进行事务提交 con.commit(null); } catch (SQLException ex) { throw new TransactionSystemException("Could not commit JDBC transaction", ex); } } @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException { //获取事务对象 ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) status.getTransaction(); //通过事务对象获取数据库连接 DatabaseConnection con = txObject.getConnectionHolder().getConnection(); if (status.isDebug()) { logger.debug("Rolling back JDBC transaction on Connection [" + con + "]"); } try { //通过调用数据库连接的回滚方法完成事务回滚操作 con.rollback(null); //直接回滚了,如果要回滚到savepoint,需要txObject.getConnectionHolder().createSavepoint() } catch (SQLException ex) { throw new TransactionSystemException("Could not roll back JDBC transaction", ex); } } //设置回滚 @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) status.getTransaction(); if (status.isDebug()) { logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() + "] rollback-only"); } txObject.setRollbackOnly(); } //操作完成之后清除操作 protected void doCleanupAfterCompletion(Object transaction) { ConnectionSourceTransactionObject txObject = (ConnectionSourceTransactionObject) transaction; //移除当前线程绑定的ConnectionHolder if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.unbindResource(this.connectionSource); } DatabaseConnection con = txObject.getConnectionHolder().getConnection(); try { //如果事务对象保存了自动事务提交属性,则设置数据库连接的自动事务提交属性 if (txObject.isMustRestoreAutoCommit()) { con.setAutoCommit(true); } //事务结束后重置数据库连接 // DataSourceUtils.resetConnectionAfterTransaction(con); } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } //如果事务对象中有新的ConnectionHolder if (txObject.isNewConnectionHolder()) { if (logger.isDebugEnabled()) { logger.debug("Releasing JDBC Connection [" + con + "] after transaction"); } //释放数据库连接 try { connectionSource.releaseConnection(con); } catch (SQLException ex) { new TransactionSystemException(ex.getMessage(), ex); } } //清除事务对象的ConnectionHolder txObject.getConnectionHolder().clear(); } //数据源事务处理器对象构造方法的回调函数 public void afterPropertiesSet() { if (getConnectionSource() == null) { throw new IllegalArgumentException("Property 'connectionSource' is required"); } } @Override public void setBeanFactory(BeanFactory arg0) throws BeansException { // TODO Auto-generated method stub com.j256.ormlite.misc.TransactionManager a; //TODO 参考的代码 } }