org.springframework.transaction.TransactionDefinition Java Examples

The following examples show how to use org.springframework.transaction.TransactionDefinition. 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: EclipseLinkJpaDialect.java    From spring-analysis-note with MIT License 9 votes vote down vote up
@Override
@Nullable
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
		// (since Spring 4.1.2)
		UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
		uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
		// Begin an early transaction to force EclipseLink to get a JDBC Connection
		// so that Spring can manage transactions with JDBC as well as EclipseLink.
		entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
	}

	return null;
}
 
Example #2
Source File: MicroServiceTemplateSupport.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public Object execGroovyRetObjByDbTranNest(String groovyName, String methodName, Integer nestDef,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    if(nestDef==null){
	    	nestDef=TransactionDefinition.PROPAGATION_REQUIRED;
	    }
	    def.setPropagationBehavior(nestDef);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
Example #3
Source File: HibernateExtendedJpaDialect.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
 public Object beginTransaction(final EntityManager entityManager, 
 		final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
 	
 	Session session = (Session) entityManager.getDelegate();
 	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
 		getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
 	}
 	entityManager.getTransaction().begin();
 	logger.debug("Transaction started");
 	session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
	 logger.debug("The connection instance is " + connection.toString());
	 logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() 
			 + " and the isolation level set on the transaction is " + definition.getIsolationLevel() );
	 DataSourceUtils.prepareConnectionForTransaction(connection, definition);
}
 	});
 	return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
 }
 
Example #4
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionCommitWithPropagationSupports() {
	given(pmf.getPersistenceManager()).willReturn(pm);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	final List l = new ArrayList();
	l.add("test");
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
			assertTrue("Is not new transaction", !status.isNewTransaction());
			PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
			return l;
		}
	});
	assertTrue("Correct result list", result == l);

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	verify(pm, times(2)).close();
}
 
Example #5
Source File: SampleDataLoader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init() {
	log.info("Initializing " + getClass().getName());
	if(cmAdmin == null) {
		return;
	}
	if(loadSampleData) {
		loginToSakai();
		PlatformTransactionManager tm = (PlatformTransactionManager)beanFactory.getBean("org.sakaiproject.springframework.orm.hibernate.GlobalTransactionManager");
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = tm.getTransaction(def);
		try {
			load();
		} catch (Exception e) {
			log.error("Unable to load CM data: " + e);
			tm.rollback(status);
		} finally {
			if(!status.isCompleted()) {
				tm.commit(status);
			}
		}
		logoutFromSakai();
	} else {
		if(log.isInfoEnabled()) log.info("Skipped CM data load");
	}
}
 
Example #6
Source File: Neo4jTransactionUtils.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
/**
 * Maps a Spring {@link TransactionDefinition transaction definition} to a native Neo4j driver transaction.
 * Only the default isolation leven ({@link TransactionDefinition#ISOLATION_DEFAULT}) and
 * {@link TransactionDefinition#PROPAGATION_REQUIRED propagation required} behaviour are supported.
 *
 * @param definition The transaction definition passed to a Neo4j transaction manager
 * @return A Neo4j native transaction configuration
 */
static TransactionConfig createTransactionConfigFrom(TransactionDefinition definition) {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		throw new InvalidIsolationLevelException(
			"Neo4jTransactionManager is not allowed to support custom isolation levels.");
	}

	int propagationBehavior = definition.getPropagationBehavior();
	if (!(propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRED || propagationBehavior == TransactionDefinition.PROPAGATION_REQUIRES_NEW)) {
		throw new IllegalTransactionStateException("Neo4jTransactionManager only supports 'required' or 'requires new' propagation.");
	}

	TransactionConfig.Builder builder = TransactionConfig.builder();
	if (definition.getTimeout() > 0) {
		builder = builder.withTimeout(Duration.ofSeconds(definition.getTimeout()));
	}

	return builder.build();
}
 
Example #7
Source File: ReactiveTransactionSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void existingTransaction() {
	ReactiveTransactionManager tm = new ReactiveTestTransactionManager(true, true);

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertNotNull(actual.getTransaction());
				assertFalse(actual.isNewTransaction());
			}).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertNotNull(actual.getTransaction());
				assertFalse(actual.isNewTransaction());
			}).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertNotNull(actual.getTransaction());
				assertFalse(actual.isNewTransaction());
			}).verifyComplete();
}
 
Example #8
Source File: RuleBasedTransactionAttributeTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testToStringMatchesEditor() {
	List<RollbackRuleAttribute> list = new LinkedList<RollbackRuleAttribute>();
	list.add(new NoRollbackRuleAttribute("Throwable"));
	RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list);

	TransactionAttributeEditor tae = new TransactionAttributeEditor();
	tae.setAsText(rta.toString());
	rta = (RuleBasedTransactionAttribute) tae.getValue();

	assertFalse(rta.rollbackOn(new Throwable()));
	assertFalse(rta.rollbackOn(new RuntimeException()));
	assertFalse(rta.rollbackOn(new MyRuntimeException("")));
	assertFalse(rta.rollbackOn(new Exception()));
	assertFalse(rta.rollbackOn(new IOException()));
}
 
Example #9
Source File: TransactionAttributeSourceEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void matchesAll() throws Exception {
	editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED");
	TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();

	checkTransactionProperties(tas, Object.class.getMethod("hashCode"),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("equals", Object.class),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait"),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait", long.class),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait", long.class, int.class),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("notify"),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("notifyAll"),
			TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("toString"),
			TransactionDefinition.PROPAGATION_REQUIRED);
}
 
Example #10
Source File: TransactionAttributeSourceEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void matchesAll() throws Exception {
	editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED");
	TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue();

	checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("equals", new Class[] { Object.class }),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait", (Class[]) null),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class }),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class, int.class }),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("notify", (Class[]) null),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("notifyAll", (Class[]) null),
		TransactionDefinition.PROPAGATION_REQUIRED);
	checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null),
		TransactionDefinition.PROPAGATION_REQUIRED);
}
 
Example #11
Source File: WebSphereUowTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void propagationNestedFailsInCaseOfExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown NestedTransactionNotSupportedException");
	}
	catch (NestedTransactionNotSupportedException ex) {
		// expected
	}
}
 
Example #12
Source File: TransactionAttributeEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testValidPropagationCodeAndIsolationCodeAndRollbackRules1() {
	TransactionAttributeEditor pe = new TransactionAttributeEditor();
	pe.setAsText("PROPAGATION_MANDATORY,ISOLATION_REPEATABLE_READ,timeout_10,-IOException,+MyRuntimeException");
	TransactionAttribute ta = (TransactionAttribute) pe.getValue();
	assertNotNull(ta);
	assertEquals(TransactionDefinition.PROPAGATION_MANDATORY, ta.getPropagationBehavior());
	assertEquals(TransactionDefinition.ISOLATION_REPEATABLE_READ, ta.getIsolationLevel());
	assertEquals(10, ta.getTimeout());
	assertFalse(ta.isReadOnly());
	assertTrue(ta.rollbackOn(new RuntimeException()));
	assertFalse(ta.rollbackOn(new Exception()));
	// Check for our bizarre customized rollback rules
	assertTrue(ta.rollbackOn(new IOException()));
	assertTrue(!ta.rollbackOn(new MyRuntimeException("")));
}
 
Example #13
Source File: WaitingQueueSubscriptionProcessor.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
public void handleWaitingTickets() {
    Map<Boolean, List<Event>> activeEvents = eventManager.getActiveEvents().stream()
        .collect(Collectors.partitioningBy(this::isWaitingListFormEnabled));
    activeEvents.get(true).forEach(event -> {
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        try {
            ticketReservationManager.revertTicketsToFreeIfAccessRestricted(event.getId());
            revertTicketToFreeIfCategoryIsExpired(event);
            distributeAvailableSeats(event);
            transactionManager.commit(transaction);
        } catch(Exception ex) {
            if(!(ex instanceof TransactionException)) {
                transactionManager.rollback(transaction);
            }
            log.error("cannot process waiting list for event {}", event.getShortName(), ex);
        }
    });
    activeEvents.get(false).forEach(eventManager::resetReleasedTickets);
}
 
Example #14
Source File: PersistenceContextTransactionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionCommitWithSharedEntityManagerAndPropagationSupports() {
	given(manager.isOpen()).willReturn(true);

	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			bean.sharedEntityManager.clear();
			return null;
		}
	});

	verify(manager).clear();
	verify(manager).close();
}
 
Example #15
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test public void testTransactionWithPropagationNotSupported() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example #16
Source File: TransactionContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
TransactionContext(TestContext testContext, PlatformTransactionManager transactionManager,
		TransactionDefinition transactionDefinition, boolean defaultRollback) {
	this.testContext = testContext;
	this.transactionManager = transactionManager;
	this.transactionDefinition = transactionDefinition;
	this.defaultRollback = defaultRollback;
	this.flaggedForRollback = defaultRollback;
}
 
Example #17
Source File: TransactionAttributeSourceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void matchAlwaysTransactionAttributeSource() throws Exception {
	MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource();
	TransactionAttribute ta = tas.getTransactionAttribute(Object.class.getMethod("hashCode"), null);
	assertNotNull(ta);
	assertTrue(TransactionDefinition.PROPAGATION_REQUIRED == ta.getPropagationBehavior());

	tas.setTransactionAttribute(new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS));
	ta = tas.getTransactionAttribute(IOException.class.getMethod("getMessage"), IOException.class);
	assertNotNull(ta);
	assertTrue(TransactionDefinition.PROPAGATION_SUPPORTS == ta.getPropagationBehavior());
}
 
Example #18
Source File: TransactionalRepositoryDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void findAllQuery() {
  @SuppressWarnings("unchecked")
  Query<Entity> query = mock(Query.class);
  transactionalRepo.findAll(query);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).findAll(query);
}
 
Example #19
Source File: WebSphereUowTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
public UOWActionAdapter(TransactionDefinition definition, TransactionCallback<T> callback,
		boolean actualTransaction, boolean newTransaction, boolean newSynchronization, boolean debug) {

	this.definition = definition;
	this.callback = callback;
	this.actualTransaction = actualTransaction;
	this.newTransaction = newTransaction;
	this.newSynchronization = newSynchronization;
	this.debug = debug;
}
 
Example #20
Source File: TransactionContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
TransactionContext(TestContext testContext, PlatformTransactionManager transactionManager,
		TransactionDefinition transactionDefinition, boolean defaultRollback) {

	this.testContext = testContext;
	this.transactionManager = transactionManager;
	this.transactionDefinition = transactionDefinition;
	this.defaultRollback = defaultRollback;
	this.flaggedForRollback = defaultRollback;
}
 
Example #21
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example #22
Source File: SpringTxManagerProxy.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
 * @param txOption e.q. TransactionDefinition.PROPAGATION_REQUIRES_NEW
 * @param timeout Set the timeout to apply in seconds. Default timeout is {@link org.springframework.transaction.TransactionDefinition#TIMEOUT_DEFAULT TIMEOUT_DEFAULT} (-1).
 * @return IbisTransaction
 */
public static TransactionDefinition getTransactionDefinition(int txOption, int timeout) {
	DefaultTransactionDefinition result=new DefaultTransactionDefinition(txOption);
	if (timeout > 0) {
		result.setTimeout(timeout);
	}
	return result; 
}
 
Example #23
Source File: TransactionUtil.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 开启新事务
 */
public static TransactionStatus beginNewTransaction() {
	DefaultTransactionDefinition td = new DefaultTransactionDefinition(
			TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	TransactionStatus status = getTransactionManager().getTransaction(td);
	return status;
}
 
Example #24
Source File: TransactionAttributeSourceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void nameMatchTransactionAttributeSourceMostSpecificMethodNameIsDefinitelyMatched()
		throws NoSuchMethodException {
	NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource();
	Properties attributes = new Properties();
	attributes.put("*", "PROPAGATION_REQUIRED");
	attributes.put("hashCode", "PROPAGATION_MANDATORY");
	tas.setProperties(attributes);
	TransactionAttribute ta = tas.getTransactionAttribute(
			Object.class.getMethod("hashCode", (Class[]) null), null);
	assertNotNull(ta);
	assertEquals(TransactionDefinition.PROPAGATION_MANDATORY, ta.getPropagationBehavior());
}
 
Example #25
Source File: TransactionAttributeEditorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testValidPropagationCodeAndIsolationCode() {
	TransactionAttributeEditor pe = new TransactionAttributeEditor();
	pe.setAsText("PROPAGATION_REQUIRED, ISOLATION_READ_UNCOMMITTED");
	TransactionAttribute ta = (TransactionAttribute) pe.getValue();
	assertTrue(ta != null);
	assertTrue(ta.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED);
	assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
}
 
Example #26
Source File: LocalDTSManager.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public IDTSStore initStore() {
	jdbcTemplate = new JdbcTemplate(dataSource);
	transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
	transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	return new LocalDTSStore(jdbcTemplate, transactionTemplate);
}
 
Example #27
Source File: TransactionalRepositoryDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void addStream() {
  @SuppressWarnings("unchecked")
  Stream<Entity> entityStream = mock(Stream.class);
  transactionalRepo.add(entityStream);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).add(entityStream);
}
 
Example #28
Source File: TransactionalRepositoryDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void findAllStream() {
  @SuppressWarnings("unchecked")
  Stream<Object> entityIds = mock(Stream.class);
  transactionalRepo.findAll(entityIds);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).findAll(entityIds);
}
 
Example #29
Source File: HibernateTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionCommitWithEntityInterceptor() throws Exception {
	Interceptor entityInterceptor = mock(Interceptor.class);
	Connection con = mock(Connection.class);
	final SessionFactory sf = mock(SessionFactory.class);
	ImplementingSession session = mock(ImplementingSession.class);
	SessionBuilder options = mock(SessionBuilder.class);
	Transaction tx = mock(Transaction.class);

	given(sf.withOptions()).willReturn(options);
	given(options.interceptor(entityInterceptor)).willReturn(options);
	given(options.openSession()).willReturn(session);
	given(session.beginTransaction()).willReturn(tx);
	given(session.isOpen()).willReturn(true);
	given(session.isConnected()).willReturn(true);
	given(session.connection()).willReturn(con);

	HibernateTransactionManager tm = new HibernateTransactionManager(sf);
	tm.setEntityInterceptor(entityInterceptor);
	tm.setAllowResultAccessAfterCompletion(true);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		public void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
		}
	});

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	verify(session).close();
	verify(tx).commit();
}
 
Example #30
Source File: RuleBasedTransactionAttributeTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check that a rule can cause commit on a IOException
 * when Exception prompts a rollback.
 */
@Test
public void testRuleForCommitOnSubclassOfChecked() {
	List<RollbackRuleAttribute> list = new LinkedList<>();
	// Note that it's important to ensure that we have this as
	// a FQN: otherwise it will match everything!
	list.add(new RollbackRuleAttribute("java.lang.Exception"));
	list.add(new NoRollbackRuleAttribute("IOException"));
	RuleBasedTransactionAttribute rta = new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, list);

	assertTrue(rta.rollbackOn(new RuntimeException()));
	assertTrue(rta.rollbackOn(new Exception()));
	// Check that default behaviour is overridden
	assertFalse(rta.rollbackOn(new IOException()));
}