1 package org.hibernate.engine; 3 4 import org.apache.commons.logging.Log; 5 import org.apache.commons.logging.LogFactory; 6 import org.hibernate.HibernateException; 7 import org.hibernate.exception.JDBCExceptionHelper; 8 9 import javax.transaction.SystemException ; 10 import javax.transaction.Transaction ; 11 import javax.transaction.TransactionManager ; 12 import java.io.Serializable ; 13 import java.sql.Connection ; 14 import java.sql.SQLException ; 15 16 22 public abstract class TransactionHelper { 23 private static final Log log = LogFactory.getLog( TransactionHelper.class ); 24 25 28 protected abstract Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException ; 29 30 33 public Serializable doWorkInNewTransaction(SessionImplementor session) 34 throws HibernateException { 35 36 TransactionManager tm = session.getFactory().getTransactionManager(); 41 Transaction surroundingTransaction = null; Connection conn = null; String sql = null; boolean isJta = tm != null; 45 boolean catchedException = false; 46 try { 47 if ( isJta ) { 48 surroundingTransaction = tm.suspend(); 51 if ( log.isDebugEnabled() ) { 52 log.debug( "surrounding tx suspended" ); 53 } 54 tm.begin(); 55 conn = session.getBatcher().openConnection(); 57 } 58 else { 59 conn = session.getBatcher().openConnection(); 61 if ( conn.getAutoCommit() ) conn.setAutoCommit( false ); 62 } 63 64 Serializable result = doWorkInCurrentTransaction( conn, sql ); 65 66 if ( isJta ) { 68 tm.commit(); 69 } 70 else { 71 conn.commit(); 72 } 73 return result; 74 } 75 catch ( SQLException sqle ) { 76 catchedException = true; 77 if ( isJta ) { 78 try { 79 tm.rollback(); 80 } 81 catch( Throwable t ) { 82 } 84 } 85 throw JDBCExceptionHelper.convert( 86 session.getFactory().getSQLExceptionConverter(), 87 sqle, 88 "could not get or update next value", 89 sql 90 ); 91 } 92 catch ( Exception e ) { 93 catchedException = true; 94 if ( isJta ) { 95 try { 96 tm.rollback(); 97 throw new HibernateException( e ); 98 } 99 catch ( SystemException e1 ) { 100 throw new HibernateException( e1 ); 101 } 102 } 103 else { 104 throw new HibernateException( e ); 105 } 106 } 107 finally { 108 if ( isJta ) { 109 try { 110 session.getBatcher().closeConnection( conn ); 111 } 112 catch ( Exception e ) { 113 } 115 if ( isJta && surroundingTransaction != null ) { 117 try { 118 tm.resume( surroundingTransaction ); 119 if ( log.isDebugEnabled() ) { 120 log.debug( "surrounding tx resumed" ); 121 } 122 } 123 catch ( Exception e ) { 124 if ( ! catchedException ) throw new HibernateException( e ); 126 } 127 } 128 } 129 else { 130 session.getBatcher().closeConnection( conn ); 131 } 132 } 133 } 134 } 135 | Popular Tags |