org.hibernate.resource.transaction.spi.TransactionStatus Java Examples

The following examples show how to use org.hibernate.resource.transaction.spi.TransactionStatus. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionsTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void jdbc() {
	//tag::transactions-api-jdbc-example[]
	StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
			// "jdbc" is the default, but for explicitness
			.applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jdbc" )
			.build();

	Metadata metadata = new MetadataSources( serviceRegistry )
			.addAnnotatedClass( Customer.class )
			.getMetadataBuilder()
			.build();

	SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
			.build();

	Session session = sessionFactory.openSession();
	try {
		// calls Connection#setAutoCommit( false ) to
		// signal start of transaction
		session.getTransaction().begin();

		session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" )
				.executeUpdate();

		// calls Connection#commit(), if an error
		// happens we attempt a rollback
		session.getTransaction().commit();
	}
	catch ( Exception e ) {
		// we may need to rollback depending on
		// where the exception happened
		if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE
				|| session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {
			session.getTransaction().rollback();
		}
		// handle the underlying error
	}
	finally {
		session.close();
		sessionFactory.close();
	}
	//end::transactions-api-jdbc-example[]
}
 
Example #2
Source File: UnitOfWorkInvokerFactoryTest.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    exchange = mock(Exchange.class);
    BindingOperationInfo boi = mock(BindingOperationInfo.class);
    when(exchange.getBindingOperationInfo()).thenReturn(boi);
    OperationInfo oi = mock(OperationInfo.class);
    when(boi.getOperationInfo()).thenReturn(oi);
    invokerBuilder = new UnitOfWorkInvokerFactory();
    fooService = new FooService();
    sessionFactory = mock(SessionFactory.class);
    session = mock(Session.class);
    when(sessionFactory.openSession()).thenReturn(session);
    transaction = mock(Transaction.class);
    when(session.getTransaction()).thenReturn(transaction);
    when(transaction.getStatus()).thenReturn(TransactionStatus.ACTIVE);
}
 
Example #3
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example #4
Source File: CacheHibernateStoreSessionListener.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
        try {
            Transaction tx = hibSes.getTransaction();

            if (commit) {
                if (hibSes.isDirty())
                    hibSes.flush();

                if (tx.getStatus() == TransactionStatus.ACTIVE)
                    tx.commit();
            }
            else if (tx.getStatus().canRollback())
                tx.rollback();
        }
        catch (HibernateException e) {
            throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
        }
        finally {
            hibSes.close();
        }
    }
}
 
Example #5
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example #6
Source File: CacheHibernateStoreSessionListener.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
        try {
            Transaction tx = hibSes.getTransaction();

            if (commit) {
                if (hibSes.isDirty())
                    hibSes.flush();

                if (tx.getStatus() == TransactionStatus.ACTIVE)
                    tx.commit();
            }
            else if (tx.getStatus().canRollback())
                tx.rollback();
        }
        catch (HibernateException e) {
            throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
        }
        finally {
            hibSes.close();
        }
    }
}
 
Example #7
Source File: Handler.java    From MirServer-Netty with GNU General Public License v3.0 6 votes vote down vote up
protected void exce(ChannelHandlerContext ctx, ClientPacket packet) throws Exception {
	session = Session.getSession(ctx);
	if(null == session){
		logger.debug("new session for {}",ctx);
		session = Session.create(ctx);
	}
	DB.getSession().getTransaction().begin();
	try{
		onPacket(packet);
		if(DB.getSession().getTransaction().getStatus().isOneOf(TransactionStatus.ACTIVE))
			DB.getSession().getTransaction().commit();
	}catch(Exception e){
		logger.error("onPacket error, {}", packet.protocol , e);
		if(DB.getSession().isOpen())
			DB.getSession().getTransaction().rollback();
	}

}
 
Example #8
Source File: JtaTransactionAdapterUserTransactionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void begin() {
	try {
		if ( getStatus() == TransactionStatus.NOT_ACTIVE ) {
			log.trace( "Calling UserTransaction#begin" );
			userTransaction.begin();
			initiator = true;
			log.trace( "Called UserTransaction#begin" );
		}
		else {
			log.trace( "Skipping TransactionManager#begin due to already active transaction" );
		}
	}
	catch (Exception e) {
		throw new TransactionException( "JTA UserTransaction#begin failed", e );
	}
}
 
Example #9
Source File: JtaTransactionAdapterTransactionManagerImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void begin() {
	try {
		if ( getStatus() == TransactionStatus.NOT_ACTIVE ) {
			log.trace( "Calling TransactionManager#begin" );
			transactionManager.begin();
			initiator = true;
			log.trace( "Called TransactionManager#begin" );
		}
		else {
			log.trace( "Skipping TransactionManager#begin due to already active transaction" );
		}
	}
	catch (Exception e) {
		throw new TransactionException( "JTA TransactionManager#begin failed", e );
	}
}
 
Example #10
Source File: AbstractLogicalConnectionImplementor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void begin() {
	try {
		if ( !doConnectionsFromProviderHaveAutoCommitDisabled() ) {
			log.trace( "Preparing to begin transaction via JDBC Connection.setAutoCommit(false)" );
			getConnectionForTransactionManagement().setAutoCommit( false );
			log.trace( "Transaction begun via JDBC Connection.setAutoCommit(false)" );
		}
		status = TransactionStatus.ACTIVE;
	}
	catch( SQLException e ) {
		throw new TransactionException( "JDBC begin transaction failed: ", e );
	}
}
 
Example #11
Source File: AbstractHibernateMemoryTest.java    From livingdoc-confluence with GNU General Public License v3.0 5 votes vote down vote up
private void rollbackIfNecessary() {
    if (transaction == null) {
        return;
    }
    if(transaction.getStatus() != TransactionStatus.COMMITTED){
        transaction.rollback();
    }
}
 
Example #12
Source File: CacheHibernateBlobStore.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Ends hibernate session.
 *
 * @param ses Hibernate session.
 * @param tx Cache ongoing transaction.
 */
private void end(Session ses, Transaction tx) {
    // Commit only if there is no cache transaction,
    // otherwise sessionEnd() will do all required work.
    if (tx == null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();

        ses.close();
    }
}
 
Example #13
Source File: CacheHibernateBlobStore.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Ends hibernate session.
 *
 * @param ses Hibernate session.
 * @param tx Cache ongoing transaction.
 */
private void end(Session ses, Transaction tx) {
    // Commit only if there is no cache transaction,
    // otherwise sessionEnd() will do all required work.
    if (tx == null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();

        ses.close();
    }
}
 
Example #14
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isTransactionFlushable() {
	if ( getCurrentTransaction() == null ) {
		// assume it is flushable - CMT, auto-commit, etc
		return true;
	}
	final TransactionStatus status = getCurrentTransaction().getStatus();
	return status == TransactionStatus.ACTIVE || status == TransactionStatus.COMMITTING;
}
 
Example #15
Source File: JdbcResourceLocalTransactionCoordinatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void rollback() {
	try {
		TransactionStatus status = jdbcResourceTransaction.getStatus();
		if ( ( rollbackOnly && status != TransactionStatus.NOT_ACTIVE ) || status == TransactionStatus.ACTIVE ) {
			jdbcResourceTransaction.rollback();
			JdbcResourceLocalTransactionCoordinatorImpl.this.afterCompletionCallback( false );
		}
	}
	finally {
		rollbackOnly = false;
	}

	// no-op otherwise.
}
 
Example #16
Source File: TransactionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean getRollbackOnly() {
	if ( !isActive() ) {
		if ( jpaCompliance.isJpaTransactionComplianceEnabled() ) {
			throw new IllegalStateException(
					"JPA compliance dictates throwing IllegalStateException when #getRollbackOnly " +
							"is called on non-active transaction"
			);
		}
	}

	return getStatus() == TransactionStatus.MARKED_ROLLBACK;
}
 
Example #17
Source File: TransactionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransactionStatus getStatus() {
	if ( transactionDriverControl == null ) {
		if ( session.isOpen() ) {
			transactionDriverControl = transactionCoordinator.getTransactionDriverControl();
		}
		else {
			return TransactionStatus.NOT_ACTIVE;
		}
	}
	return transactionDriverControl.getStatus();
}
 
Example #18
Source File: TransactionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void rollback() {
	if ( !isActive() ) {
		if ( jpaCompliance.isJpaTransactionComplianceEnabled() ) {

			throw new IllegalStateException(
					"JPA compliance dictates throwing IllegalStateException when #rollback " +
							"is called on non-active transaction"
			);
		}
	}

	TransactionStatus status = getStatus();
	if ( status == TransactionStatus.ROLLED_BACK || status == TransactionStatus.NOT_ACTIVE ) {
		// Allow rollback() calls on completed transactions, just no-op.
		LOG.debug( "rollback() called on an inactive transaction" );
		return;
	}

	if ( !status.canRollback() ) {
		throw new TransactionException( "Cannot rollback transaction in current status [" + status.name() + "]" );
	}

	LOG.debug( "rolling back" );

	if ( status != TransactionStatus.FAILED_COMMIT || allowFailedCommitToPhysicallyRollback() ) {
		internalGetTransactionDriverControl().rollback();
	}
}
 
Example #19
Source File: WrapperServlet.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void rollbackTransaction(Session session, UnitOfWork uow) {
    if (uow.transactional()) {
        Transaction txn = session.getTransaction();
        if (txn != null && session.getTransaction().getStatus() != TransactionStatus.ACTIVE) {
            txn.rollback();
        }
    }

}
 
Example #20
Source File: AbstractLogicalConnectionImplementor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void rollback() {
	try {
		log.trace( "Preparing to rollback transaction via JDBC Connection.rollback()" );
		getConnectionForTransactionManagement().rollback();
		status = TransactionStatus.ROLLED_BACK;
		log.trace( "Transaction rolled-back via JDBC Connection.rollback()" );
	}
	catch( SQLException e ) {
		status = TransactionStatus.FAILED_ROLLBACK;
		throw new TransactionException( "Unable to rollback against JDBC Connection", e );
	}

	afterCompletion();
}
 
Example #21
Source File: AbstractLogicalConnectionImplementor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void resetConnection(boolean initiallyAutoCommit) {
	try {
		if ( initiallyAutoCommit ) {
			log.trace( "re-enabling auto-commit on JDBC Connection after completion of JDBC-based transaction" );
			getConnectionForTransactionManagement().setAutoCommit( true );
			status = TransactionStatus.NOT_ACTIVE;
		}
	}
	catch ( Exception e ) {
		log.debug(
				"Could not re-enable auto-commit on JDBC Connection after completion of JDBC-based transaction : " + e
		);
	}
}
 
Example #22
Source File: AbstractLogicalConnectionImplementor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void commit() {
	try {
		log.trace( "Preparing to commit transaction via JDBC Connection.commit()" );
		getConnectionForTransactionManagement().commit();
		status = TransactionStatus.COMMITTED;
		log.trace( "Transaction committed via JDBC Connection.commit()" );
	}
	catch( SQLException e ) {
		status = TransactionStatus.FAILED_COMMIT;
		throw new TransactionException( "Unable to commit against JDBC Connection", e );
	}

	afterCompletion();
}
 
Example #23
Source File: WrapperServlet.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void commitTransaction(Session session, UnitOfWork uow) {
    if (uow.transactional()) {
        Transaction txn = session.getTransaction();
        if (txn != null && session.getTransaction().getStatus() != TransactionStatus.ACTIVE) {
            txn.commit();
        }
    }

}
 
Example #24
Source File: Transaction.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * If transaction is present and active then commit.
 */
private void success() {
    org.hibernate.Transaction txn = session.getTransaction();
    if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
        txn.commit();
    }
}
 
Example #25
Source File: JtaTransactionCoordinatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void explicitJoin() {
	if ( synchronizationRegistered ) {
		log.debug( "JTA transaction was already joined (RegisteredSynchronization already registered)" );
		return;
	}

	if ( getTransactionDriverControl().getStatus() != TransactionStatus.ACTIVE ) {
		throw new TransactionRequiredForJoinException(
				"Explicitly joining a JTA transaction requires a JTA transaction be currently active"
		);
	}

	joinJtaTransaction();
}
 
Example #26
Source File: StatusTranslator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static TransactionStatus translate(int status) {
	TransactionStatus transactionStatus = null;
	switch ( status ) {
		case Status.STATUS_ACTIVE:
			transactionStatus = TransactionStatus.ACTIVE;
			break;
		case Status.STATUS_PREPARED:
			transactionStatus = TransactionStatus.ACTIVE;
			break;
		case Status.STATUS_PREPARING:
			transactionStatus = TransactionStatus.ACTIVE;
			break;
		case Status.STATUS_COMMITTING:
			transactionStatus = TransactionStatus.COMMITTING;
			break;
		case Status.STATUS_ROLLING_BACK:
			transactionStatus = TransactionStatus.ROLLING_BACK;
			break;
		case Status.STATUS_NO_TRANSACTION:
			transactionStatus = TransactionStatus.NOT_ACTIVE;
			break;
		case Status.STATUS_COMMITTED:
			transactionStatus = TransactionStatus.COMMITTED;
			break;
		case Status.STATUS_ROLLEDBACK:
			transactionStatus = TransactionStatus.ROLLED_BACK;
			break;
		case Status.STATUS_MARKED_ROLLBACK:
			transactionStatus = TransactionStatus.MARKED_ROLLBACK;
			break;
		default:
			break;
	}
	if ( transactionStatus == null ) {
		throw new TransactionException( "TransactionManager reported transaction status as unknwon" );
	}
	return transactionStatus;
}
 
Example #27
Source File: JtaTransactionAdapterUserTransactionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransactionStatus getStatus() {
	try {
		return StatusTranslator.translate( userTransaction.getStatus() );
	}
	catch (SystemException e) {
		throw new TransactionException( "JTA TransactionManager#getStatus failed", e );
	}
}
 
Example #28
Source File: Transaction.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * If transaction is present and active then rollback.
 */
private void error() {
    org.hibernate.Transaction txn = session.getTransaction();
    if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
        txn.rollback();
    }
}
 
Example #29
Source File: JtaTransactionAdapterTransactionManagerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransactionStatus getStatus() {
	try {
		return StatusTranslator.translate( transactionManager.getStatus() );
	}
	catch (SystemException e) {
		throw new TransactionException( "JTA TransactionManager#getStatus failed", e );
	}
}
 
Example #30
Source File: UnitOfWorkInvoker.java    From dropwizard-jaxws with Apache License 2.0 5 votes vote down vote up
/**
 * @see io.dropwizard.hibernate.UnitOfWorkAspect#rollbackTransaction()
 */
private void rollbackTransaction(Session session, UnitOfWork unitOfWork) {
    if (unitOfWork.transactional()) {
        final Transaction txn = session.getTransaction();
        if (txn != null && txn.getStatus().equals(TransactionStatus.ACTIVE)) {
            txn.rollback();
        }
    }
}