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 Project: spring-analysis-note   Author: Vip-Augus   File: EclipseLinkJpaDialect.java    License: 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 Project: sdn-rx   Author: neo4j   File: Neo4jTransactionUtils.java    License: 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 #3
Source Project: bamboobsc   Author: billchen198318   File: HibernateExtendedJpaDialect.java    License: 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 Project: spring4-understanding   Author: langtianya   File: RuleBasedTransactionAttributeTests.java    License: 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 #5
Source Project: java-technology-stack   Author: codeEngraver   File: TransactionAttributeSourceEditorTests.java    License: 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 #6
Source Project: spring4-understanding   Author: langtianya   File: TransactionAttributeSourceEditorTests.java    License: 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 #7
Source Project: spring-analysis-note   Author: Vip-Augus   File: WebSphereUowTransactionManagerTests.java    License: 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 #8
Source Project: alf.io   Author: alfio-event   File: WaitingQueueSubscriptionProcessor.java    License: 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 #9
Source Project: spring4-understanding   Author: langtianya   File: PersistenceContextTransactionTests.java    License: 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 #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: TransactionAttributeEditorTests.java    License: 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 #11
Source Project: nh-micro   Author: jeffreyning   File: MicroServiceTemplateSupport.java    License: 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 #12
Source Project: spring-analysis-note   Author: Vip-Augus   File: ReactiveTransactionSupportTests.java    License: 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 #13
Source Project: sakai   Author: sakaiproject   File: SampleDataLoader.java    License: 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 #14
Source Project: spring4-understanding   Author: langtianya   File: JdoTransactionManagerTests.java    License: 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 #15
Source Project: sdn-rx   Author: neo4j   File: ReactiveNeo4jTransactionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<Void> doBegin(TransactionSynchronizationManager transactionSynchronizationManager, Object transaction,
		TransactionDefinition transactionDefinition) throws TransactionException {

	return Mono.defer(() -> {
		ReactiveNeo4jTransactionObject transactionObject = extractNeo4jTransaction(transaction);

		TransactionConfig transactionConfig = createTransactionConfigFrom(transactionDefinition);
		boolean readOnly = transactionDefinition.isReadOnly();

		transactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly);

		return databaseSelectionProvider.getDatabaseSelection()
			.switchIfEmpty(Mono.just(DatabaseSelection.undecided()))
			.map(databaseName -> new Neo4jTransactionContext(databaseName.getValue(), bookmarkManager.getBookmarks()))
			.map(context -> Tuples.of(context, this.driver.rxSession(sessionConfig(readOnly, context.getBookmarks(), context.getDatabaseName()))))
			.flatMap(contextAndSession -> Mono
					.from(contextAndSession.getT2().beginTransaction(transactionConfig))
					.map(nativeTransaction -> new ReactiveNeo4jTransactionHolder(contextAndSession.getT1(), contextAndSession.getT2(), nativeTransaction))
			)
			.doOnNext(transactionHolder -> {
				transactionHolder.setSynchronizedWithTransaction(true);
				transactionObject.setResourceHolder(transactionHolder);
				transactionSynchronizationManager.bindResource(this.driver, transactionHolder);
			});

	}).then();
}
 
Example #16
Source Project: spring-ldap   Author: spring-projects   File: AbstractCompensatingTransactionManagerDelegate.java    License: Apache License 2.0 5 votes vote down vote up
public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
	try {
		CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction;
		if (txObject.getHolder() == null) {
			CompensatingTransactionHolderSupport contextHolder = getNewHolder();
			txObject.setHolder(contextHolder);

			TransactionSynchronizationManager.bindResource(getTransactionSynchronizationKey(), contextHolder);
		}
	}
	catch (Exception e) {
		throw new CannotCreateTransactionException("Could not create DirContext instance for transaction", e);
	}
}
 
Example #17
Source Project: spring-boot-mybatisplus-multiple-datasource   Author: yujunhao8831   File: TransactionalConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 支持当前事务;如果不存在创建一个新的
 */
private RuleBasedTransactionAttribute requiredTransactionRule () {
    RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute();
    required.setRollbackRules( Collections.singletonList( new RollbackRuleAttribute( Exception.class ) ) );
    required.setPropagationBehavior( TransactionDefinition.PROPAGATION_REQUIRED );
    required.setTimeout( TransactionDefinition.TIMEOUT_DEFAULT );
    return required;
}
 
Example #18
Source Project: spring4-understanding   Author: langtianya   File: JpaTransactionManagerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionCommitWithPropagationSupports() {
	given(manager.isOpen()).willReturn(true);

	final List<String> l = new ArrayList<String>();
	l.add("test");

	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue(!TransactionSynchronizationManager.hasResource(factory));
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertTrue(!status.isNewTransaction());
			EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
			return l;
		}
	});
	assertSame(l, result);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
Example #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: JpaTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testTransactionCommitWithPropagationSupports() {
	given(manager.isOpen()).willReturn(true);

	final List<String> l = new ArrayList<>();
	l.add("test");

	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue(!TransactionSynchronizationManager.hasResource(factory));
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertTrue(!status.isNewTransaction());
			EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
			return l;
		}
	});
	assertSame(l, result);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
Example #20
Source Project: micronaut-sql   Author: micronaut-projects   File: SpringTransactionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void begin(TransactionContext context) {
    TransactionDefinition definition = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_NESTED);
    TransactionStatus status = this.transactionManager.getTransaction(definition);
    context.transaction(new SpringTransaction(status));
}
 
Example #21
Source Project: spring-analysis-note   Author: Vip-Augus   File: JpaTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testTransactionRollbackWithPreboundAndPropagationSupports() {
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));

	try {
		tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.hasResource(factory));
				assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
				assertTrue(!status.isNewTransaction());
				EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
				status.setRollbackOnly();
				return null;
			}
		});

		assertTrue(TransactionSynchronizationManager.hasResource(factory));
		assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(factory);
	}

	verify(manager).flush();
	verify(manager).clear();
}
 
Example #22
@Test
void delete() {
  Entity entity = mock(Entity.class);
  transactionalRepo.delete(entity);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).delete(entity);
}
 
Example #23
Source Project: NoteBlog   Author: miyakowork   File: ArticleServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public boolean postArticle(Article article, String tagNames) {
    if (LangUtils.string.isEmpty(tagNames)) {
        throw new RuntimeException("tagName不能为空!");
    }
    String[] tagNameArray = tagNames.split(",");
    DefaultTransactionDefinition def = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus status = tm.getTransaction(def);
    try {
        //博客没啥并发吧,那就按秒来吧
        long articleId = System.currentTimeMillis() / 1000;
        article.setId(articleId);
        getSumByFilterContent(article);
        int savePostArticle = articleRepository.savePk(article);
        if (savePostArticle == 0) {
            throw new RuntimeException("博文未发布成功...");
        }
        int cnt = 0;
        for (String name : Arrays.asList(tagNameArray)) {
            long tagId;
            if (tagRepository.countByName(name) == 0) {
                tagId = tagRepository.save(Tag.builder().name(name).build()).getId();
            } else {
                tagId = tagRepository.findIdByName(name);
            }
            tagReferRepository.save(TagRefer.builder().referId(articleId).tagId(tagId).show(cnt < 4).type(TagType.article.name()).build());
            cnt++;
        }
        tm.commit(status);
        return true;
    } catch (Exception e) {
        tm.rollback(status);
        log.error("发布博文出错,回滚数据...", e);
        throw new RuntimeException(e);
    }
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: DefaultJpaDialect.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * This implementation invokes the standard JPA {@code Transaction.begin}
 * method. Throws an InvalidIsolationLevelException if a non-default isolation
 * level is set.
 * <p>This implementation does not return any transaction data Object, since there
 * is no state to be kept for a standard JPA transaction. Hence, subclasses do not
 * have to care about the return value ({@code null}) of this implementation
 * and are free to return their own transaction data Object.
 * @see javax.persistence.EntityTransaction#begin
 * @see org.springframework.transaction.InvalidIsolationLevelException
 * @see #cleanupTransaction
 */
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		throw new InvalidIsolationLevelException(getClass().getSimpleName() +
				" does not support custom isolation levels due to limitations in standard JPA. " +
				"Specific arrangements may be implemented in custom JpaDialect variants.");
	}
	entityManager.getTransaction().begin();
	return null;
}
 
Example #25
Source Project: spring-analysis-note   Author: Vip-Augus   File: TransactionAwareCacheDecoratorTests.java    License: 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 #26
Source Project: spring-cloud-gcp   Author: spring-cloud   File: DatastoreTransactionManagerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetTransactionActive() {
	this.manager.doBegin(this.tx, TransactionDefinition.withDefaults());
	when(this.transaction.isActive()).thenReturn(true);
	this.tx.setTransaction(this.transaction);
	assertThat(this.manager.doGetTransaction()).isSameAs(this.tx);
}
 
Example #27
@Test
void deleteById() {
  Object id = mock(Object.class);
  transactionalRepo.deleteById(id);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).deleteById(id);
}
 
Example #28
@Test
void deleteStream() {
  @SuppressWarnings("unchecked")
  Stream<Entity> entityStream = mock(Stream.class);
  transactionalRepo.delete(entityStream);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).delete(entityStream);
}
 
Example #29
Source Project: effectivejava   Author: ftomassetti   File: DataSourceTransactionManagerTests.java    License: Apache License 2.0 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 #30
@Test
void findAllStream() {
  @SuppressWarnings("unchecked")
  Stream<Object> entityIds = mock(Stream.class);
  transactionalRepo.findAll(entityIds);
  verify(transactionManager).getTransaction(any(TransactionDefinition.class));
  verify(delegateRepository).findAll(entityIds);
}