Java Code Examples for org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()

The following examples show how to use org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly() . 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: SpringJtaSynchronizationAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * JTA {@code beforeCompletion} callback: just invoked before commit.
 * <p>In case of an exception, the JTA transaction will be marked as rollback-only.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit
 */
@Override
public void beforeCompletion() {
	try {
		boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
		this.springSynchronization.beforeCommit(readOnly);
	}
	catch (RuntimeException | Error ex) {
		setRollbackOnlyIfPossible();
		throw ex;
	}
	finally {
		// Process Spring's beforeCompletion early, in order to avoid issues
		// with strict JTA implementations that issue warnings when doing JDBC
		// operations after transaction completion (e.g. Connection.getWarnings).
		this.beforeCompletionCalled = true;
		this.springSynchronization.beforeCompletion();
	}
}
 
Example 2
Source File: L2CacheRepositoryDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testFindAllFetchTransactionReadonly() {
  boolean previousReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
  try {
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);

    Fetch fetch = mock(Fetch.class);
    List<Object> ids = asList("0", "1", "2");
    Entity entity0 = when(mock(Entity.class).getIdValue()).thenReturn("0").getMock();
    Entity entity1 = when(mock(Entity.class).getIdValue()).thenReturn("1").getMock();
    Entity entity2 = when(mock(Entity.class).getIdValue()).thenReturn("2").getMock();
    List<Entity> entities = asList(entity0, entity1, entity2);
    when(l2Cache.getBatch(delegateRepository, ids, fetch)).thenReturn(entities);
    assertEquals(
        entities, l2CacheRepositoryDecorator.findAll(ids.stream(), fetch).collect(toList()));
  } finally {
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(previousReadOnly);
  }
}
 
Example 3
Source File: L2CacheRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private List<Entity> findAllCache(List<Object> ids, Fetch fetch) {
  if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
    List<Entity> unorderedEntities = l2Cache.getBatch(delegate(), ids, fetch);
    return createOrderedEntities(ids, unorderedEntities);
  } else {
    String entityTypeId = getEntityType().getId();
    Multimap<Boolean, Object> partitionedIds =
        Multimaps.index(
            ids, id -> transactionInformation.isEntityDirty(EntityKey.create(entityTypeId, id)));
    Collection<Object> cleanIds = partitionedIds.get(false);
    Collection<Object> dirtyIds = partitionedIds.get(true);

    List<Entity> batch = l2Cache.getBatch(delegate(), cleanIds, fetch);
    Map<Object, Entity> result = newHashMap(uniqueIndex(batch, Entity::getIdValue));
    result.putAll(
        delegate().findAll(dirtyIds.stream(), fetch).collect(toMap(Entity::getIdValue, e -> e)));

    return ids.stream().filter(result::containsKey).map(result::get).collect(toList());
  }
}
 
Example 4
Source File: L2CacheRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves a batch of Entity IDs.
 *
 * <p>If currently in transaction, splits the ids into those that have been dirtied in the current
 * transaction and those that have been left untouched. The untouched ids are loaded through the
 * cache, the dirtied ids are loaded from the decorated repository directly.
 *
 * @param ids list of entity IDs to retrieve
 * @return List of {@link Entity}s, missing ones excluded.
 */
private List<Entity> findAllCache(List<Object> ids) {
  if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
    List<Entity> unorderedEntities = l2Cache.getBatch(delegate(), ids);
    return createOrderedEntities(ids, unorderedEntities);
  } else {
    String entityTypeId = getEntityType().getId();
    Multimap<Boolean, Object> partitionedIds =
        Multimaps.index(
            ids, id -> transactionInformation.isEntityDirty(EntityKey.create(entityTypeId, id)));
    Collection<Object> cleanIds = partitionedIds.get(false);
    Collection<Object> dirtyIds = partitionedIds.get(true);

    Map<Object, Entity> result =
        newHashMap(uniqueIndex(l2Cache.getBatch(delegate(), cleanIds), Entity::getIdValue));
    result.putAll(
        delegate().findAll(dirtyIds.stream()).collect(toMap(Entity::getIdValue, e -> e)));

    return ids.stream().filter(result::containsKey).map(result::get).collect(toList());
  }
}
 
Example 5
Source File: SpringJtaSynchronizationAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * JTA {@code beforeCompletion} callback: just invoked before commit.
 * <p>In case of an exception, the JTA transaction will be marked as rollback-only.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit
 */
@Override
public void beforeCompletion() {
	try {
		boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
		this.springSynchronization.beforeCommit(readOnly);
	}
	catch (RuntimeException ex) {
		setRollbackOnlyIfPossible();
		throw ex;
	}
	catch (Error err) {
		setRollbackOnlyIfPossible();
		throw err;
	}
	finally {
		// Process Spring's beforeCompletion early, in order to avoid issues
		// with strict JTA implementations that issue warnings when doing JDBC
		// operations after transaction completion (e.g. Connection.getWarnings).
		this.beforeCompletionCalled = true;
		this.springSynchronization.beforeCompletion();
	}
}
 
Example 6
Source File: AlfrescoTransactionSupport.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @return      Returns the read-write state of the current transaction
 * @since 2.1.4
 */
public static TxnReadState getTransactionReadState()
{
    if (!TransactionSynchronizationManager.isSynchronizationActive())
    {
        return TxnReadState.TXN_NONE;
    }
    // Find the read-write state of the txn
    else if (TransactionSynchronizationManager.isCurrentTransactionReadOnly())
    {
        return TxnReadState.TXN_READ_ONLY;
    }
    else
    {
        return TxnReadState.TXN_READ_WRITE;
    }
}
 
Example 7
Source File: SpringJtaSynchronizationAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * JTA {@code beforeCompletion} callback: just invoked before commit.
 * <p>In case of an exception, the JTA transaction will be marked as rollback-only.
 * @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit
 */
@Override
public void beforeCompletion() {
	try {
		boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
		this.springSynchronization.beforeCommit(readOnly);
	}
	catch (RuntimeException | Error ex) {
		setRollbackOnlyIfPossible();
		throw ex;
	}
	finally {
		// Process Spring's beforeCompletion early, in order to avoid issues
		// with strict JTA implementations that issue warnings when doing JDBC
		// operations after transaction completion (e.g. Connection.getWarnings).
		this.beforeCompletionCalled = true;
		this.springSynchronization.beforeCompletion();
	}
}
 
Example 8
Source File: L2CacheRepositoryDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testFindAllTransactionReadonly() {
  boolean previousReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
  try {
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);

    List<Object> ids = asList("0", "1", "2");
    Entity entity0 = when(mock(Entity.class).getIdValue()).thenReturn("0").getMock();
    Entity entity1 = when(mock(Entity.class).getIdValue()).thenReturn("1").getMock();
    Entity entity2 = when(mock(Entity.class).getIdValue()).thenReturn("2").getMock();
    List<Entity> entities = asList(entity0, entity1, entity2);
    when(l2Cache.getBatch(delegateRepository, ids)).thenReturn(entities);
    assertEquals(entities, l2CacheRepositoryDecorator.findAll(ids.stream()).collect(toList()));
  } finally {
    TransactionSynchronizationManager.setCurrentTransactionReadOnly(previousReadOnly);
  }
}
 
Example 9
Source File: RocketMqSendUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
public static void sendMq(List<MqBaseModel> mqBaseModels){
    // 判断是否存在事务,为空则说明不存在
    String currentTransactionName  = TransactionSynchronizationManager.getCurrentTransactionName();
    boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
    if (StrUtil.isBlank(currentTransactionName) || readOnly){
        MqNoTransactionSynchronizationAdapter.commit(mqBaseModels);
    } else {
        TransactionSynchronizationManager.registerSynchronization(new MqTransactionSynchronizationAdapter(mqBaseModels));
    }
}
 
Example 10
Source File: SpringJtaSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 11
Source File: TransactionAwareSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Binds the configured session to Spring's transaction manager strategy if there's no session.
    *
    * @return Returns the configured session, or the one managed by Spring. Never returns null.
    */
   @Override
   public Session currentSession() {
try {
    Session s = defaultSessionContext.currentSession();
    return s;
} catch (HibernateException cause) {

    // There's no session bound to the current thread. Let's open one if
    // needed.
    if (ManagedSessionContext.hasBind(sessionFactory)) {
	return localSessionContext.currentSession();
    }

    Session session;
    session = sessionFactory.openSession();
    TransactionAwareSessionContext.logger.warn("No Session bound to current Thread. Opened new Session ["
	    + session + "]. Transaction: " + session.getTransaction());

    if (registerSynchronization(session)) {
	// Normalizes Session flush mode, defaulting it to AUTO. Required for
	// synchronization. LDEV-4696 Updated for Hibernate 5.3. See SPR-14364.
	FlushMode flushMode = session.getHibernateFlushMode();

	if (FlushMode.MANUAL.equals(flushMode)
		&& !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
	    session.setFlushMode(FlushMode.AUTO);
	}
    }
    ManagedSessionContext.bind(session);

    return session;
}
   }
 
Example 12
Source File: SpringJtaSessionContext.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 13
Source File: SpringSessionContext.java    From lemon with Apache License 2.0 5 votes vote down vote up
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager
            .getResource(this.sessionFactory);

    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();

        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new SpringSessionSynchronization(
                            sessionHolder, this.sessionFactory));
            sessionHolder.setSynchronizedWithTransaction(true);

            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();

            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager
                            .isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }

        return session;
    } else {
        throw new HibernateException("No Session found for current thread");
    }
}
 
Example 14
Source File: SpringJtaSessionContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 15
Source File: TransactionRoutingDataSource.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected Object determineCurrentLookupKey() {
    return TransactionSynchronizationManager.isCurrentTransactionReadOnly() ?
        DataSourceType.READ_ONLY :
        DataSourceType.READ_WRITE;
}
 
Example 16
Source File: L1CacheRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean useCache() {
  return cacheable && !TransactionSynchronizationManager.isCurrentTransactionReadOnly();
}
 
Example 17
Source File: IsolationLevelDataSourceAdapter.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Determine the current read-only flag: by default,
 * the transaction's read-only hint.
 * @return whether there is a read-only hint for the current scope
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
 */
@Nullable
protected Boolean getCurrentReadOnlyFlag() {
	boolean txReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
	return (txReadOnly ? Boolean.TRUE : null);
}
 
Example 18
Source File: IsolationLevelDataSourceAdapter.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determine the current read-only flag: by default,
 * the transaction's read-only hint.
 * @return whether there is a read-only hint for the current scope
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
 */
protected Boolean getCurrentReadOnlyFlag() {
	boolean txReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
	return (txReadOnly ? Boolean.TRUE : null);
}
 
Example 19
Source File: IsolationLevelDataSourceAdapter.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Determine the current read-only flag: by default,
 * the transaction's read-only hint.
 * @return whether there is a read-only hint for the current scope
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
 */
@Nullable
protected Boolean getCurrentReadOnlyFlag() {
	boolean txReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
	return (txReadOnly ? Boolean.TRUE : null);
}
 
Example 20
Source File: IsolationLevelDataSourceAdapter.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the current read-only flag: by default,
 * the transaction's read-only hint.
 * @return whether there is a read-only hint for the current scope
 * @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
 */
protected Boolean getCurrentReadOnlyFlag() {
	boolean txReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
	return (txReadOnly ? Boolean.TRUE : null);
}