org.springframework.transaction.interceptor.DefaultTransactionAttribute Java Examples

The following examples show how to use org.springframework.transaction.interceptor.DefaultTransactionAttribute. 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: TransactionAdviceConfig.java    From SpringBoot2.0 with Apache License 2.0 6 votes vote down vote up
@Bean
public TransactionInterceptor txAdvice() {

    DefaultTransactionAttribute required = new DefaultTransactionAttribute();
    required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    DefaultTransactionAttribute readonly = new DefaultTransactionAttribute();
    readonly.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    readonly.setReadOnly(true);

    NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
    source.addTransactionalMethod("add*", required);
    source.addTransactionalMethod("save*", required);
    source.addTransactionalMethod("delete*", required);
    source.addTransactionalMethod("update*", required);
    source.addTransactionalMethod("exec*", required);
    source.addTransactionalMethod("set*", required);
    source.addTransactionalMethod("do*", required);

    source.addTransactionalMethod("get*", readonly);
    source.addTransactionalMethod("query*", readonly);
    source.addTransactionalMethod("find*", readonly);
    source.addTransactionalMethod("list*", readonly);
    source.addTransactionalMethod("count*", readonly);
    return new TransactionInterceptor(transactionManager, source);
}
 
Example #2
Source File: TransactionAwareCacheDecoratorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void evictTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
	cache.evict(key);
	assertEquals("123", target.get(key, String.class));
	this.txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #3
Source File: TransactionAwareCacheDecoratorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void clearTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
	cache.clear();
	assertEquals("123", target.get(key, String.class));
	this.txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #4
Source File: TransactionAwareCacheDecoratorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void clearTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
	cache.clear();
	assertEquals("123", target.get(key, String.class));
	this.txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #5
Source File: TransactionAwareCacheDecoratorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void clearTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute(
			TransactionDefinition.PROPAGATION_REQUIRED));
	cache.clear();
	assertEquals("123", target.get(key, String.class));
	txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #6
Source File: TransactionAwareCacheDecoratorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void evictTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));
	cache.evict(key);
	assertEquals("123", target.get(key, String.class));
	this.txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #7
Source File: TransactionAwareCacheDecoratorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void evictTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);
	Object key = new Object();
	cache.put(key, "123");


	TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute(
			TransactionDefinition.PROPAGATION_REQUIRED));
	cache.evict(key);
	assertEquals("123", target.get(key, String.class));
	txManager.commit(status);

	assertNull(target.get(key));
}
 
Example #8
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockTx).commit();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #9
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
	Object testEntity = new Object();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
	MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
	pui.setTransactionType(PersistenceUnitTransactionType.JTA);

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockEm).joinTransaction();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #10
Source File: TransactionJobDemo.java    From SpringAll with MIT License 5 votes vote down vote up
private Step step() {
    DefaultTransactionAttribute attribute = new DefaultTransactionAttribute();
    attribute.setPropagationBehavior(Propagation.REQUIRED.value());
    attribute.setIsolationLevel(Isolation.DEFAULT.value());
    attribute.setTimeout(30);

    return stepBuilderFactory.get("step")
            .<String, String>chunk(2)
            .reader(listItemReader())
            .writer(list -> list.forEach(System.out::println))
            .readerIsTransactionalQueue()
            .transactionAttribute(attribute)
            .build();
}
 
Example #11
Source File: TransactionAwareCacheDecoratorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void putTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);

	TransactionStatus status = txManager.getTransaction(new DefaultTransactionAttribute(
			TransactionDefinition.PROPAGATION_REQUIRED));

	Object key = new Object();
	cache.put(key, "123");
	assertNull(target.get(key));
	txManager.commit(status);

	assertEquals("123", target.get(key, String.class));
}
 
Example #12
Source File: TransactionAwareCacheDecoratorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void putTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);

	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));

	Object key = new Object();
	cache.put(key, "123");
	assertNull(target.get(key));
	this.txManager.commit(status);

	assertEquals("123", target.get(key, String.class));
}
 
Example #13
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
	Object testEntity = new Object();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
	MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
	pui.setTransactionType(PersistenceUnitTransactionType.JTA);

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockEm).joinTransaction();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #14
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockTx).commit();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #15
Source File: TransactionAwareCacheDecoratorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void putTransactional() {
	Cache target = new ConcurrentMapCache("testCache");
	Cache cache = new TransactionAwareCacheDecorator(target);

	TransactionStatus status = this.txManager.getTransaction(
			new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED));

	Object key = new Object();
	cache.put(key, "123");
	assertNull(target.get(key));
	this.txManager.commit(status);

	assertEquals("123", target.get(key, String.class));
}
 
Example #16
Source File: ProgrammaticTransactionConfig.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
public TransactionInterceptor defaultTransactionInterceptor(PlatformTransactionManager transactionManager,
                                                            List<Class<? extends Exception>> additionalRollbackRuleExceptions) {
    TransactionInterceptor transactionInterceptor = new TransactionInterceptor();
    Properties transactionAttributes = new Properties();

    List<RollbackRuleAttribute> rollbackRules = Lists.newArrayList();
    rollbackRules.add(new RollbackRuleAttribute(Exception.class));
    //回滚异常
    if (additionalRollbackRuleExceptions != null && !additionalRollbackRuleExceptions.isEmpty()) {
        for (Class<? extends Exception> clazz : additionalRollbackRuleExceptions) {
            rollbackRules.add(new RollbackRuleAttribute(clazz));
        }
    }
    DefaultTransactionAttribute readOnlyTransactionAttributes =
            new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
    readOnlyTransactionAttributes.setReadOnly(true);

    RuleBasedTransactionAttribute writeTransactionAttributes =
            new RuleBasedTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED, rollbackRules);

    String readOnlyTransactionAttributesDefinition = readOnlyTransactionAttributes.toString();
    String writeTransactionAttributesDefinition = writeTransactionAttributes.toString();
    // read-only
    transactionAttributes.setProperty("is*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("has*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("get*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("list*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("search*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("find*", readOnlyTransactionAttributesDefinition);
    transactionAttributes.setProperty("count*", readOnlyTransactionAttributesDefinition);
    // write et rollback-rule
    transactionAttributes.setProperty("*", writeTransactionAttributesDefinition);

    transactionInterceptor.setTransactionAttributes(transactionAttributes);
    transactionInterceptor.setTransactionManager(this.transactionManager);
    return transactionInterceptor;
}
 
Example #17
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception {
	Object testEntity = new Object();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
	MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo());
	pui.setTransactionType(PersistenceUnitTransactionType.JTA);

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockEm).joinTransaction();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #18
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransaction() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	jpatm.commit(txStatus);

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockTx).commit();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #19
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);
	willThrow(new OptimisticLockException()).given(mockTx).commit();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	try {
		jpatm.commit(txStatus);
		fail("Should have thrown OptimisticLockingFailureException");
	}
	catch (OptimisticLockingFailureException ex) {
		// expected
	}

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #20
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);
	willThrow(new OptimisticLockException()).given(mockTx).commit();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	try {
		jpatm.commit(txStatus);
		fail("Should have thrown OptimisticLockingFailureException");
	}
	catch (OptimisticLockingFailureException ex) {
		// expected
	}

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #21
Source File: TransactionalJdbcIdempotentChecker.java    From qmq with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean doIsProcessed(Message message) throws Exception {
    currentStatus.set(this.transactionManager.getTransaction(new DefaultTransactionAttribute()));
    return idempotentChecker.doIsProcessed(message);
}
 
Example #22
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel)
		throws Exception {

	if (executionPhase != sql.executionPhase()) {
		return;
	}

	MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
				mergedSqlConfig, executionPhase, testContext));
	}

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
	populator.setSeparator(mergedSqlConfig.getSeparator());
	populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
	populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
	populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
	populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
	populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

	String[] scripts = getScripts(sql, testContext, classLevel);
	scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
	List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(
			testContext.getApplicationContext(), scripts);
	for (String stmt : sql.statements()) {
		if (StringUtils.hasText(stmt)) {
			stmt = stmt.trim();
			scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
		}
	}
	populator.setScripts(scriptResources.toArray(new Resource[0]));
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
	}

	String dsName = mergedSqlConfig.getDataSource();
	String tmName = mergedSqlConfig.getTransactionManager();
	DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
	PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
	boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

	if (txMgr == null) {
		Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"cannot execute SQL scripts using Transaction Mode " +
				"[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
		Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"supply at least a DataSource or PlatformTransactionManager.", testContext));
		// Execute scripts directly against the DataSource
		populator.execute(dataSource);
	}
	else {
		DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
		// Ensure user configured an appropriate DataSource/TransactionManager pair.
		if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
			throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " +
					"the configured DataSource [%s] (named '%s') is not the one associated with " +
					"transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
					dsName, txMgr.getClass().getName(), tmName));
		}
		if (dataSource == null) {
			dataSource = dataSourceFromTxMgr;
			Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " +
					"test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
					testContext, txMgr.getClass().getName(), tmName));
		}
		final DataSource finalDataSource = dataSource;
		int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW :
				TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
				testContext, new DefaultTransactionAttribute(propagation));
		new TransactionTemplate(txMgr, txAttr).execute(status -> {
			populator.execute(finalDataSource);
			return null;
		});
	}
}
 
Example #23
Source File: LocalContainerEntityManagerFactoryBeanTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception {
	Object testEntity = new Object();

	EntityTransaction mockTx = mock(EntityTransaction.class);
	willThrow(new OptimisticLockException()).given(mockTx).commit();

	// This one's for the tx (shared)
	EntityManager sharedEm = mock(EntityManager.class);
	given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction());

	// This is the application-specific one
	EntityManager mockEm = mock(EntityManager.class);
	given(mockEm.getTransaction()).willReturn(mockTx);

	given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm);

	LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();

	JpaTransactionManager jpatm = new JpaTransactionManager();
	jpatm.setEntityManagerFactory(cefb.getObject());

	TransactionStatus txStatus = jpatm.getTransaction(new DefaultTransactionAttribute());

	EntityManagerFactory emf = cefb.getObject();
	assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());

	assertNotSame("EMF must be proxied", mockEmf, emf);
	EntityManager em = emf.createEntityManager();
	em.joinTransaction();
	assertFalse(em.contains(testEntity));

	try {
		jpatm.commit(txStatus);
		fail("Should have thrown OptimisticLockingFailureException");
	}
	catch (OptimisticLockingFailureException ex) {
		// expected
	}

	cefb.destroy();

	verify(mockTx).begin();
	verify(mockEm).contains(testEntity);
	verify(mockEmf).close();
}
 
Example #24
Source File: SqlScriptsTestExecutionListener.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel)
		throws Exception {

	if (executionPhase != sql.executionPhase()) {
		return;
	}

	MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
				mergedSqlConfig, executionPhase, testContext));
	}

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
	populator.setSeparator(mergedSqlConfig.getSeparator());
	populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
	populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
	populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
	populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
	populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

	String[] scripts = getScripts(sql, testContext, classLevel);
	scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
	List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(
			testContext.getApplicationContext(), scripts);
	for (String stmt : sql.statements()) {
		if (StringUtils.hasText(stmt)) {
			stmt = stmt.trim();
			scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
		}
	}
	populator.setScripts(scriptResources.toArray(new Resource[0]));
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
	}

	String dsName = mergedSqlConfig.getDataSource();
	String tmName = mergedSqlConfig.getTransactionManager();
	DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
	PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
	boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

	if (txMgr == null) {
		Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"cannot execute SQL scripts using Transaction Mode " +
				"[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
		Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"supply at least a DataSource or PlatformTransactionManager.", testContext));
		// Execute scripts directly against the DataSource
		populator.execute(dataSource);
	}
	else {
		DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
		// Ensure user configured an appropriate DataSource/TransactionManager pair.
		if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
			throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " +
					"the configured DataSource [%s] (named '%s') is not the one associated with " +
					"transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
					dsName, txMgr.getClass().getName(), tmName));
		}
		if (dataSource == null) {
			dataSource = dataSourceFromTxMgr;
			Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " +
					"test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
					testContext, txMgr.getClass().getName(), tmName));
		}
		final DataSource finalDataSource = dataSource;
		int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW :
				TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
				testContext, new DefaultTransactionAttribute(propagation));
		new TransactionTemplate(txMgr, txAttr).execute(status -> {
			populator.execute(finalDataSource);
			return null;
		});
	}
}
 
Example #25
Source File: ComposedRunnerVisitorConfiguration.java    From composed-task-runner with Apache License 2.0 3 votes vote down vote up
/**
 * Using the default transaction attribute for the job will cause the
 * TaskLauncher not to see the latest state in the database but rather
 * what is in its transaction.  By setting isolation to READ_COMMITTED
 * The task launcher can see latest state of the db.  Since the changes
 * to the task execution are done by the tasks.

 * @return DefaultTransactionAttribute with isolation set to READ_COMMITTED.
 */
private TransactionAttribute getTransactionAttribute() {
	DefaultTransactionAttribute defaultTransactionAttribute =
			new DefaultTransactionAttribute();
	defaultTransactionAttribute.setIsolationLevel(
			Isolation.READ_COMMITTED.value());
	return defaultTransactionAttribute;
}
 
Example #26
Source File: ComposedTaskRunnerStepFactory.java    From composed-task-runner with Apache License 2.0 3 votes vote down vote up
/**
 * Using the default transaction attribute for the job will cause the
 * TaskLauncher not to see the latest state in the database but rather
 * what is in its transaction.  By setting isolation to READ_COMMITTED
 * The task launcher can see latest state of the db.  Since the changes
 * to the task execution are done by the tasks.

 * @return DefaultTransactionAttribute with isolation set to READ_COMMITTED.
 */
private TransactionAttribute getTransactionAttribute() {
	DefaultTransactionAttribute defaultTransactionAttribute =
			new DefaultTransactionAttribute();
	defaultTransactionAttribute.setIsolationLevel(
			Isolation.READ_COMMITTED.value());
	return defaultTransactionAttribute;
}
 
Example #27
Source File: ComposedTaskRunnerStepFactory.java    From spring-cloud-dataflow with Apache License 2.0 3 votes vote down vote up
/**
 * Using the default transaction attribute for the job will cause the
 * TaskLauncher not to see the latest state in the database but rather
 * what is in its transaction.  By setting isolation to READ_COMMITTED
 * The task launcher can see latest state of the db.  Since the changes
 * to the task execution are done by the tasks.

 * @return DefaultTransactionAttribute with isolation set to READ_COMMITTED.
 */
private TransactionAttribute getTransactionAttribute() {
	DefaultTransactionAttribute defaultTransactionAttribute =
			new DefaultTransactionAttribute();
	defaultTransactionAttribute.setIsolationLevel(
			Isolation.READ_COMMITTED.value());
	return defaultTransactionAttribute;
}
 
Example #28
Source File: ComposedRunnerVisitorConfiguration.java    From spring-cloud-dataflow with Apache License 2.0 3 votes vote down vote up
/**
 * Using the default transaction attribute for the job will cause the
 * TaskLauncher not to see the latest state in the database but rather
 * what is in its transaction.  By setting isolation to READ_COMMITTED
 * The task launcher can see latest state of the db.  Since the changes
 * to the task execution are done by the tasks.

 * @return DefaultTransactionAttribute with isolation set to READ_COMMITTED.
 */
private TransactionAttribute getTransactionAttribute() {
	DefaultTransactionAttribute defaultTransactionAttribute =
			new DefaultTransactionAttribute();
	defaultTransactionAttribute.setIsolationLevel(
			Isolation.READ_COMMITTED.value());
	return defaultTransactionAttribute;
}