下面列出了org.hibernate.resource.transaction.spi.TransactionStatus#ACTIVE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** {@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();
}
}
/** {@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();
}
}
@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.
}
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;
}
@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();
}
private void commitTransaction(Session session, UnitOfWork uow) {
if (uow.transactional()) {
Transaction txn = session.getTransaction();
if (txn != null && session.getTransaction().getStatus() != TransactionStatus.ACTIVE) {
txn.commit();
}
}
}
@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 );
}
}
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;
}
/**
* 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();
}
}
private void rollbackTransaction(Session session, UnitOfWork uow) {
if (uow.transactional()) {
Transaction txn = session.getTransaction();
if (txn != null && session.getTransaction().getStatus() != TransactionStatus.ACTIVE) {
txn.rollback();
}
}
}
/**
* 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();
}
}
public boolean hasHibernateManagedTransaction() {
return (this.sessionHolder != null &&
this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
@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[]
}
@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[]
}
@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[]
}
public boolean hasHibernateManagedTransaction() {
return (this.sessionHolder != null &&
this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
public boolean hasHibernateManagedTransaction() {
return (this.sessionHolder != null &&
this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
public boolean hasHibernateManagedTransaction() {
return (this.sessionHolder != null &&
this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}
@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;
}
}
public boolean hasHibernateManagedTransaction() {
return (this.sessionHolder != null &&
this.sessionHolder.getSession().getTransaction().getStatus() == TransactionStatus.ACTIVE);
}