javax.transaction.TransactionManager.begin()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(214)

本文整理了Java中javax.transaction.TransactionManager.begin()方法的一些代码示例,展示了TransactionManager.begin()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。TransactionManager.begin()方法的具体详情如下:
包路径:javax.transaction.TransactionManager
类名称:TransactionManager
方法名:begin

TransactionManager.begin介绍

[英]Starts a new transaction, and associate it with the calling thread.
[中]启动一个新事务,并将其与调用线程关联。

代码示例

代码示例来源:origin: wildfly/wildfly

@Override
public TransactionBatch createBatch() {
  if (this.tm == null) return NON_TX_BATCH;
  TransactionBatch batch = getCurrentBatch();
  try {
    if ((batch != null) && (batch.getState() == Batch.State.ACTIVE)) {
      return batch.interpose();
    }
    this.tm.suspend();
    this.tm.begin();
    Transaction tx = this.tm.getTransaction();
    tx.registerSynchronization(CURRENT_BATCH_SYNCHRONIZATION);
    batch = new InfinispanBatch(tx);
    setCurrentBatch(batch);
    return batch;
  } catch (RollbackException | SystemException | NotSupportedException e) {
    throw new CacheException(e);
  }
}

代码示例来源:origin: hibernate/hibernate-orm

private <T> T doInNewTransaction(HibernateCallable<T> callable, TransactionManager transactionManager) {
  try {
    // start the new isolated transaction
    transactionManager.begin();
    try {
      T result = callable.call();
      // if everything went ok, commit the isolated transaction
      transactionManager.commit();
      return result;
    }
    catch (Exception e) {
      try {
        transactionManager.rollback();
      }
      catch (Exception ignore) {
        LOG.unableToRollbackIsolatedTransaction( e, ignore );
      }
      throw new HibernateException( "Could not apply work", e );
    }
  }
  catch (SystemException e) {
    throw new HibernateException( "Unable to start isolated transaction", e );
  }
  catch (NotSupportedException e) {
    throw new HibernateException( "Unable to start isolated transaction", e );
  }
}

代码示例来源:origin: wildfly/wildfly

tm.setTransactionTimeout(timeout);
try {
  final Transaction suspended = tm.suspend();
  try {
    tm.begin();
    final Transaction transaction = tm.suspend();
    SimpleXid gtid = SimpleXid.of(getXid(transaction)).withoutBranch();
    known.put(gtid, getEntryFor(transaction, gtid));
  } catch (Throwable t) {
    if (suspended != null) try {
      tm.resume(suspended);
    } catch (InvalidTransactionException e) {
      e.addSuppressed(t);

代码示例来源:origin: spring-projects/spring-framework

@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception {
  TransactionManager tm = mock(TransactionManager.class);
  Transaction tx = mock(Transaction.class);
  given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
  given(tm.suspend()).willReturn(tx);
  JtaTransactionManager ptm = newJtaTransactionManager(tm);
  TransactionTemplate tt = new TransactionTemplate(ptm);
  tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
  assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
  tt.execute(new TransactionCallbackWithoutResult() {
    @Override
    protected void doInTransactionWithoutResult(TransactionStatus status) {
      assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
    }
  });
  assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
  verify(tm).begin();
  verify(tm).commit();
  verify(tm).resume(tx);
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testEvictAndTx() throws SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException {
 for (int i=0; i<10; i++) {
   tm.begin();
   for (int j=0; j<10; j++) cache.put(String.format("key-%s-%s", i, j), "value");
   tm.commit();
   for (int j=0; j<10; j++) assert "value".equals(cache.get(String.format("key-%s-%s", i, j))) : "Data loss on key " + String.format("key-%s-%s", i, j);
 }
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testTxCleanupWithSize() throws Exception {
   tm().begin();
   assertEquals(0, cache.size());
   TransactionTable txTable = getTransactionTable(cache);
   assertEquals(1, txTable.getLocalTransactions().size());
   tm().commit();
   assertEquals(0, txTable.getLocalTransactions().size());
  }
}

代码示例来源:origin: org.infinispan/infinispan-core

@Test (expectedExceptions = TimeoutException.class)
public void testMultiLockFailure() throws Exception {
 Cache<String, String> cache1 = cache(0), cache2 = cache(1);
 cache1.put("k1", "v");
 cache1.put("k2", "v");
 cache1.put("k3", "v");
 tm(1).begin();
 cache2.put("k3", "v2");
 tm(1).suspend();
 tm(0).begin();
 cache1.getAdvancedCache().lock(Arrays.asList("k1", "k2", "k3"));
 tm(0).rollback();
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testTransactionalReplace(Method m) throws Exception {
 assertEquals(ComponentStatus.RUNNING, cache.getStatus());
 assertNotInCacheAndStore(k(m, 1));
 assertNotInCacheAndStore(k(m, 2));
 cache.put(k(m, 2), v(m));
 tm.begin();
 cache.put(k(m, 1), v(m, 1));
 cache.replace(k(m, 2), v(m, 1));
 Transaction t = tm.suspend();
 assertNotInCacheAndStore(k(m, 1));
 assertInCacheAndStore(k(m, 2), v(m));
 tm.resume(t);
 tm.commit();
 assertInCacheAndStore(k(m, 1), v(m, 1));
 assertInCacheAndStore(k(m, 2), v(m, 1));
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testPutIfAbsent() throws Throwable {
 Object k1 = getKeyForCache(0);
 tm(0).begin();
 assertNull(cache(0).putIfAbsent(k1, "v1"));
 Transaction suspendedTx = tm(0).suspend();
 cache(0).put(k1, "v2");
 assertEquals(cache(0).get(k1), "v2");
 assertEquals(cache(1).get(k1), "v2");
 suspendedTx.commit();
 assertEquals("v1", cache(0).get(k1));
 assertEquals("v1", cache(1).get(k1));
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testPferNoAutoCommitExplicitTransaction() throws Exception {
 tm().begin();
 cache.putForExternalRead("k1","v");
 tm().commit();
 assert cache.get("k1").equals("v"); //here is the failure!
}

代码示例来源:origin: org.infinispan/infinispan-core

private void assertAllHaveNewValue(Object key) throws Exception {
 for (Cache c : caches()) {
   Object actual;
   TestingUtil.getTransactionManager(c).begin();
   actual = c.get(key);
   TestingUtil.getTransactionManager(c).commit();
   assertEquals(actual, "newValue");
 }
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testNotROWhenHasWrites() throws Exception {
 tm().begin();
 cache.put("k", "v");
 assert TestingUtil.extractLockManager(cache).isLocked("k");
 Transaction transaction = tm().suspend();
 LocalXaTransaction localTransaction = (LocalXaTransaction) txTable().getLocalTransaction(transaction);
 assert localTransaction != null && !localTransaction.isReadOnly();
}

代码示例来源:origin: hibernate/hibernate-orm

TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
Session s = openSession();
Map foo = new HashMap();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
Session s1 = openSession();
foo = ( Map ) s1.get( "Item", "Foo" );
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
Session s2 = openSession();
foo = ( Map ) s2.get( "Item", "Foo" );
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().commit();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
s1 = openSession();
s1.createCriteria( "Item" ).list();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
s2 = openSession();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
s2 = openSession();
s2.createCriteria( "Item" ).list();
TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin();
s = openSession();
s.createQuery( "delete from Item" ).executeUpdate();

代码示例来源:origin: org.infinispan/infinispan-core

public void simpleReplicationTest() throws Exception {
 TransactionManager tm = TestingUtil.getTransactionManager(cache1);
 tm.begin();
 cache1.put("key", "value");
 tm.commit();
 assertEquals("value", cache2.get("key"));
}

代码示例来源:origin: kiegroup/optaplanner

protected <S extends Score, E extends AbstractTestJpaEntity<S>> void findAndAssert(
    Class<E> jpaEntityClass, Long id, S score) {
  try {
    transactionManager.begin();
    EntityManager em = entityManagerFactory.createEntityManager();
    E jpaEntity = em.find(jpaEntityClass, id);
    assertEquals(score, jpaEntity.getScore());
    transactionManager.commit();
  } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException | HeuristicRollbackException e) {
    throw new RuntimeException("Transaction failed.", e);
  }
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testTxCleanupWithEntrySet() throws Exception {
 tm().begin();
 assertEquals(0, cache.entrySet().size());
 TransactionTable txTable = getTransactionTable(cache);
 assertEquals(1, txTable.getLocalTransactions().size());
 tm().commit();
 assertEquals(0, txTable.getLocalTransactions().size());
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testSilentMultiLockFailure() throws Exception {
 Cache<String, String> cache1 = cache(0), cache2 = cache(1);
 cache1.put("k1", "v");
 cache1.put("k2", "v");
 cache1.put("k3", "v");
 tm(1).begin();
 cache2.put("k3", "v2");
 tm(1).suspend();
 tm(0).begin();
 assert !cache1.getAdvancedCache().withFlags(FAIL_SILENTLY).lock(Arrays.asList("k1", "k2", "k3"));
 tm(0).rollback();
}

代码示例来源:origin: org.infinispan/infinispan-core

public void testReplace2() throws Throwable {
 Object k1 = getKeyForCache(0);
 cache(0).put(k1, "v1");
 tm(0).begin();
 assertEquals("v1", cache(0).replace(k1, "v2"));
 Transaction suspendedTx = tm(0).suspend();
 cache(0).put(k1, "v3");
 assertEquals(cache(0).get(k1), "v3");
 assertEquals(cache(1).get(k1), "v3");
 suspendedTx.commit();
 assertEquals("v2", cache(0).get(k1));
 assertEquals("v2", cache(1).get(k1));
}

代码示例来源:origin: mulesoft/mule

@Test
public void testTxHandleCommitKeepsThreadAssociation() throws Exception {
 // don't wait for ages, has to be set before TX is begun
 tm.setTransactionTimeout(TRANSACTION_TIMEOUT_SECONDS);
 tm.begin();
 Transaction tx = tm.getTransaction();
 assertNotNull("Transaction should have started.", tx);
 assertEquals("TX should have been active", Status.STATUS_ACTIVE, tx.getStatus());
 tx.commit();
 tx = tm.getTransaction();
 assertNotNull("Committing via TX handle should NOT disassociated TX from the current thread.", tx);
 assertEquals("TX status should have been COMMITTED.", Status.STATUS_COMMITTED, tx.getStatus());
 // Remove the TX-thread association. The only public API to achieve it is suspend(),
 // technically we never resume the same transaction (TX forget).
 Transaction suspended = tm.suspend();
 assertTrue("Wrong TX suspended?.", suspended.equals(tx));
 assertNull("TX should've been disassociated from the thread.", tm.getTransaction());
 // should be no-op and never fail
 tm.resume(null);
 // ensure we don't have any TX-Thread association lurking around a main thread
 assertNull(tm.getTransaction());
}

代码示例来源:origin: wildfly/wildfly

@Override
public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException {
  // JCA 1.6 FR 13.5.6
  // The application server must set the thread context class loader to the endpoint
  // application class loader during the beforeDelivery call.
  previousClassLoader = WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(getApplicationClassLoader());
  try {
    final TransactionManager tm = getTransactionManager();
    // TODO: in violation of JCA 1.6 FR 13.5.9?
    previousTx = tm.suspend();
    boolean isTransacted = service.isDeliveryTransacted(method);
    if (isTransacted) {
      tm.begin();
      currentTx = tm.getTransaction();
      if (xaRes != null)
        currentTx.enlistResource(xaRes);
    }
  } catch (Throwable t) {
    throw new ApplicationServerInternalException(t);
  } finally {
    WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(previousClassLoader);
  }
}

相关文章