Java Code Examples for org.hibernate.resource.transaction.spi.TransactionStatus#ACTIVE

The following examples show how to use org.hibernate.resource.transaction.spi.TransactionStatus#ACTIVE . 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: 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 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: 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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: ThreadLocalSessionContext.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
@SuppressWarnings("SimplifiableIfStatement")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	final String methodName = method.getName();

	// first check methods calls that we handle completely locally:
	if ( "equals".equals( methodName ) && method.getParameterCount() == 1 ) {
		if ( args[0] == null
				|| !Proxy.isProxyClass( args[0].getClass() ) ) {
			return false;
		}
		return this.equals( Proxy.getInvocationHandler( args[0] ) );
	}
	else if ( "hashCode".equals( methodName ) && method.getParameterCount() == 0 ) {
		return this.hashCode();
	}
	else if ( "toString".equals( methodName ) && method.getParameterCount() == 0 ) {
		return String.format( Locale.ROOT, "ThreadLocalSessionContext.TransactionProtectionWrapper[%s]", realSession );
	}


	// then check method calls that we need to delegate to the real Session
	try {
		// If close() is called, guarantee unbind()
		if ( "close".equals( methodName ) ) {
			unbind( realSession.getSessionFactory() );
		}
		else if ( "getStatistics".equals( methodName )
				|| "isOpen".equals( methodName )
				|| "getListeners".equals( methodName ) ) {
			// allow these to go through the the real session no matter what
			LOG.tracef( "Allowing invocation [%s] to proceed to real session", methodName );
		}
		else if ( !realSession.isOpen() ) {
			// essentially, if the real session is closed allow any
			// method call to pass through since the real session
			// will complain by throwing an appropriate exception;
			// NOTE that allowing close() above has the same basic effect,
			//   but we capture that there simply to doAfterTransactionCompletion the unbind...
			LOG.tracef( "Allowing invocation [%s] to proceed to real (closed) session", methodName );
		}
		else if ( realSession.getTransaction().getStatus() != TransactionStatus.ACTIVE ) {
			// limit the methods available if no transaction is active
			if ( "beginTransaction".equals( methodName )
					|| "getTransaction".equals( methodName )
					|| "isTransactionInProgress".equals( methodName )
					|| "setFlushMode".equals( methodName )
					|| "getFactory".equals( methodName )
					|| "getSessionFactory".equals( methodName )
					|| "getTenantIdentifier".equals( methodName ) ) {
				LOG.tracef( "Allowing invocation [%s] to proceed to real (non-transacted) session", methodName );
			}
			else if ( "reconnect".equals( methodName ) || "disconnect".equals( methodName ) ) {
				// allow these (deprecated) methods to pass through
				LOG.tracef( "Allowing invocation [%s] to proceed to real (non-transacted) session - deprecated methods", methodName );
			}
			else {
				throw new HibernateException( "Calling method '" + methodName + "' is not valid without an active transaction (Current status: "
						+ realSession.getTransaction().getStatus() + ")" );
			}
		}
		LOG.tracef( "Allowing proxy invocation [%s] to proceed to real session", methodName );
		return method.invoke( realSession, args );
	}
	catch ( InvocationTargetException e ) {
		if (e.getTargetException() instanceof RuntimeException) {
			throw (RuntimeException)e.getTargetException();
		}
		throw e;
	}
}
 
Example 14
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public boolean hasHibernateManagedTransaction() {
	return (this.sessionHolder != null &&
			this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
 
Example 15
Source File: HibernateTransactionManager.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public boolean hasHibernateManagedTransaction() {
	return (this.sessionHolder != null &&
			this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
 
Example 16
Source File: HibernateTransactionManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
public boolean hasHibernateManagedTransaction() {
	return (this.sessionHolder != null &&
			this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
 
Example 17
Source File: HibernateTransactionManager.java    From micronaut-data with Apache License 2.0 4 votes vote down vote up
public boolean hasHibernateManagedTransaction() {
    return (this.sessionHolder != null &&
            this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
 
Example 18
Source File: TransactionsTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void bmt() {
	//tag::transactions-api-bmt-example[]
	StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
			// "jdbc" is the default, but for explicitness
			.applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta" )
			.build();

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

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

	// Note: depending on the JtaPlatform used and some optional settings,
	// the underlying transactions here will be controlled through either
	// the JTA TransactionManager or UserTransaction

	Session session = sessionFactory.openSession();
	try {
		// Assuming a JTA transaction is not already active,
		// this call the TM/UT begin method.  If a JTA
		// transaction is already active, we remember that
		// the Transaction associated with the Session did
		// not "initiate" the JTA transaction and will later
		// nop-op the commit and rollback calls...
		session.getTransaction().begin();

		session.persist( new Customer(  ) );
		Customer customer = (Customer) session.createQuery( "select c from Customer c" ).uniqueResult();

		// calls TM/UT commit method, assuming we are initiator.
		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 ) {
			// calls TM/UT commit method, assuming we are initiator;
			// otherwise marks the JTA transaction for rollback only
			session.getTransaction().rollback();
		}
		// handle the underlying error
	}
	finally {
		session.close();
		sessionFactory.close();
	}
	//end::transactions-api-bmt-example[]
}
 
Example 19
Source File: TransactionsTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void cmt() {
	//tag::transactions-api-cmt-example[]
	StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
			// "jdbc" is the default, but for explicitness
			.applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta" )
			.build();

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

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

	// Note: depending on the JtaPlatform used and some optional settings,
	// the underlying transactions here will be controlled through either
	// the JTA TransactionManager or UserTransaction

	Session session = sessionFactory.openSession();
	try {
		// Since we are in CMT, a JTA transaction would
		// already have been started.  This call essentially
		// no-ops
		session.getTransaction().begin();

		Number customerCount = (Number) session.createQuery( "select count(c) from Customer c" ).uniqueResult();

		// Since we did not start the transaction ( CMT ),
		// we also will not end it.  This call essentially
		// no-ops in terms of transaction handling.
		session.getTransaction().commit();
	}
	catch ( Exception e ) {
		// again, the rollback call here would no-op (aside from
		// marking the underlying CMT transaction for rollback only).
		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-cmt-example[]
}
 
Example 20
Source File: HibernateTransactionManager.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public boolean hasHibernateManagedTransaction() {
	return (this.sessionHolder != null &&
			this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}