Java Code Examples for org.springframework.transaction.TransactionDefinition#isReadOnly()

The following examples show how to use org.springframework.transaction.TransactionDefinition#isReadOnly() . 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: OpenJpaDialect.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
		FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
		if (fetchPlan instanceof JDBCFetchPlan) {
			IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
			((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
		}
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly()) {
		// Like with EclipseLink, make sure to start the logic transaction early so that other
		// participants using the connection (such as JdbcTemplate) run in a transaction.
		openJpaEntityManager.beginStore();
	}

	// Custom implementation for OpenJPA savepoint handling
	return new OpenJpaTransactionData(openJpaEntityManager);
}
 
Example 2
Source File: EclipseLinkJpaDialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
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 3
Source File: EclipseLinkJpaDialect.java    From java-technology-stack with MIT License 6 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 4
Source File: AbstractPlatformTransactionManager.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a TransactionStatus instance for the given arguments.
 */
protected DefaultTransactionStatus newTransactionStatus(
		TransactionDefinition definition, @Nullable Object transaction, boolean newTransaction,
		boolean newSynchronization, boolean debug, @Nullable Object suspendedResources) {

	boolean actualNewSynchronization = newSynchronization &&
			!TransactionSynchronizationManager.isSynchronizationActive();
	return new DefaultTransactionStatus(
			transaction, newTransaction, actualNewSynchronization,
			definition.isReadOnly(), debug, suspendedResources);
}
 
Example 5
Source File: DatastoreTransactionManager.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
protected void doBegin(Object transactionObject,
		TransactionDefinition transactionDefinition) throws TransactionException {
	if (transactionDefinition
			.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT
			&& transactionDefinition
					.getIsolationLevel() != TransactionDefinition.ISOLATION_SERIALIZABLE) {
		throw new IllegalStateException(
				"DatastoreTransactionManager supports only isolation level "
						+ "TransactionDefinition.ISOLATION_DEFAULT or ISOLATION_SERIALIZABLE");
	}
	if (transactionDefinition
			.getPropagationBehavior() != TransactionDefinition.PROPAGATION_REQUIRED) {
		throw new IllegalStateException(
				"DatastoreTransactionManager supports only propagation behavior "
						+ "TransactionDefinition.PROPAGATION_REQUIRED");
	}
	Tx tx = (Tx) transactionObject;
	if (transactionDefinition.isReadOnly()) {
		tx.transaction = tx.datastore.newTransaction(READ_ONLY_OPTIONS);
	}
	else {
		tx.transaction = tx.datastore.newTransaction();
	}

	TransactionSynchronizationManager.bindResource(tx.datastore, tx);
}
 
Example 6
Source File: AbstractPlatformTransactionManager.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a TransactionStatus instance for the given arguments.
 */
protected DefaultTransactionStatus newTransactionStatus(
		TransactionDefinition definition, Object transaction, boolean newTransaction,
		boolean newSynchronization, boolean debug, Object suspendedResources) {

	boolean actualNewSynchronization = newSynchronization &&
			!TransactionSynchronizationManager.isSynchronizationActive();
	return new DefaultTransactionStatus(
			transaction, newTransaction, actualNewSynchronization,
			definition.isReadOnly(), debug, suspendedResources);
}
 
Example 7
Source File: DynamicDataSourceTransactionManager.java    From dynamic-data-source-demo with Apache License 2.0 5 votes vote down vote up
/**
 * 事务开始前将数据源手动设置进去
 */
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    //若有 @Transaction 注解,并且不是只读,设置为主库
    if (!definition.isReadOnly()) {
        DynamicDataSourceHolder.routeMaster();
    }
    super.doBegin(transaction, definition);
}
 
Example 8
Source File: ChainedTransactionManager.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Create a rae TransactionStatus instance for the given arguments.
 */
protected DefaultTransactionStatus newTransactionStatus(
		TransactionDefinition definition, Object transaction) {
	// Cache debug flag to avoid repeated checks.
	boolean debugEnabled = logger.isDebugEnabled();
	
	return new DefaultTransactionStatus(
			transaction, true, true,
			definition.isReadOnly(), debugEnabled, null);
}
 
Example 9
Source File: DynamicDataSourceTransactionManager.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
/**
 * 只读事务到读库,读写事务到写库
 *
 * @param transaction
 * @param definition
 */
@Override
protected void doBegin(final Object transaction, final TransactionDefinition definition) {
    //设置数据源
    final boolean readOnly = definition.isReadOnly();
    if (readOnly) {
        DynamicDataSourceHolder.putDataSource(DynamicDataSourceType.READ);
    } else {
        DynamicDataSourceHolder.putDataSource(DynamicDataSourceType.WRITE);
    }
    super.doBegin(transaction, definition);
}
 
Example 10
Source File: ReactiveFirestoreTransactionManager.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private Mono<ReactiveFirestoreResourceHolder> startTransaction(TransactionDefinition definition) {
	TransactionOptions.Builder txOptions = definition.isReadOnly()
			? TransactionOptions.newBuilder().setReadOnly(TransactionOptions.ReadOnly.newBuilder().build())
			: TransactionOptions.newBuilder().setReadWrite(TransactionOptions.ReadWrite.newBuilder().build());

	BeginTransactionRequest beginTransactionRequest = BeginTransactionRequest.newBuilder()
			.setOptions(txOptions)
			.setDatabase(this.databasePath)
			.build();
	return ObservableReactiveUtil
			.<BeginTransactionResponse>unaryCall(
					obs -> this.firestore.beginTransaction(beginTransactionRequest, obs))
			.map(beginTransactionResponse -> new ReactiveFirestoreResourceHolder(
					beginTransactionResponse.getTransaction()));
}
 
Example 11
Source File: Neo4jTransactionManager.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
	Neo4jTransactionObject transactionObject = extractNeo4jTransaction(transaction);

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


	TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly);

	try {
		// Prepare configuration data
		Neo4jTransactionContext context = new Neo4jTransactionContext(
			databaseSelectionProvider.getDatabaseSelection().getValue(),
			bookmarkManager.getBookmarks()
		);

		// Configure and open session together with a native transaction
		Session session = this.driver
			.session(sessionConfig(readOnly, context.getBookmarks(), context.getDatabaseName()));
		Transaction nativeTransaction = session.beginTransaction(transactionConfig);

		// Synchronize on that
		Neo4jTransactionHolder transactionHolder = new Neo4jTransactionHolder(context, session, nativeTransaction);
		transactionHolder.setSynchronizedWithTransaction(true);
		transactionObject.setResourceHolder(transactionHolder);

		TransactionSynchronizationManager.bindResource(this.driver, transactionHolder);
	} catch (Exception ex) {
		throw new TransactionSystemException(String.format("Could not open a new Neo4j session: %s", ex.getMessage()));
	}
}
 
Example 12
Source File: HibernateJpaDialect.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off. " +
					"This is the case on Hibernate 3.6 by default; either switch that flag at your own risk " +
					"or upgrade to Hibernate 4.x, with 4.2+ recommended.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example 13
Source File: PostgreSqlTransactionManager.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
  MolgenisTransaction molgenisTransaction = (MolgenisTransaction) transaction;
  if (LOG.isDebugEnabled()) {
    LOG.debug("Start transaction [{}]", molgenisTransaction.getId());
  }

  super.doBegin(molgenisTransaction.getDataSourceTransaction(), definition);

  if (!definition.isReadOnly()) {
    TransactionSynchronizationManager.bindResource(
        TransactionConstants.TRANSACTION_ID_RESOURCE_NAME, molgenisTransaction.getId());
    transactionListeners.forEach(j -> j.transactionStarted(molgenisTransaction.getId()));
  }
}
 
Example 14
Source File: HibernateJpaDialect.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	if (definition instanceof ResourceTransactionDefinition &&
			((ResourceTransactionDefinition) definition).isLocalResource()) {
		// As of 5.1, we explicitly optimize for a transaction-local EntityManager,
		// aligned with native HibernateTransactionManager behavior.
		previousFlushMode = null;
		if (definition.isReadOnly()) {
			session.setDefaultReadOnly(true);
		}
	}
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example 15
Source File: DataSourceUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Prepare the given Connection with the given transaction semantics.
 * @param con the Connection to prepare
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws SQLException if thrown by JDBC methods
 * @see #resetConnectionAfterTransaction
 */
@Nullable
public static Integer prepareConnectionForTransaction(Connection con, @Nullable TransactionDefinition definition)
		throws SQLException {

	Assert.notNull(con, "No Connection specified");

	// Set read-only flag.
	if (definition != null && definition.isReadOnly()) {
		try {
			if (logger.isDebugEnabled()) {
				logger.debug("Setting JDBC Connection [" + con + "] read-only");
			}
			con.setReadOnly(true);
		}
		catch (SQLException | RuntimeException ex) {
			Throwable exToCheck = ex;
			while (exToCheck != null) {
				if (exToCheck.getClass().getSimpleName().contains("Timeout")) {
					// Assume it's a connection timeout that would otherwise get lost: e.g. from JDBC 4.0
					throw ex;
				}
				exToCheck = exToCheck.getCause();
			}
			// "read-only not supported" SQLException -> ignore, it's just a hint anyway
			logger.debug("Could not set JDBC Connection read-only", ex);
		}
	}

	// Apply specific isolation level, if any.
	Integer previousIsolationLevel = null;
	if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		if (logger.isDebugEnabled()) {
			logger.debug("Changing isolation level of JDBC Connection [" + con + "] to " +
					definition.getIsolationLevel());
		}
		int currentIsolation = con.getTransactionIsolation();
		if (currentIsolation != definition.getIsolationLevel()) {
			previousIsolationLevel = currentIsolation;
			con.setTransactionIsolation(definition.getIsolationLevel());
		}
	}

	return previousIsolationLevel;
}
 
Example 16
Source File: HibernateJpaDialect.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	if (definition instanceof ResourceTransactionDefinition &&
			((ResourceTransactionDefinition) definition).isLocalResource()) {
		// As of 5.1, we explicitly optimize for a transaction-local EntityManager,
		// aligned with native HibernateTransactionManager behavior.
		previousFlushMode = null;
		if (definition.isReadOnly()) {
			session.setDefaultReadOnly(true);
		}
	}
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example 17
Source File: DefaultTransactionDefinition.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Copy constructor. Definition can be modified through bean property setters.
 * @see #setPropagationBehavior
 * @see #setIsolationLevel
 * @see #setTimeout
 * @see #setReadOnly
 * @see #setName
 */
public DefaultTransactionDefinition(TransactionDefinition other) {
	this.propagationBehavior = other.getPropagationBehavior();
	this.isolationLevel = other.getIsolationLevel();
	this.timeout = other.getTimeout();
	this.readOnly = other.isReadOnly();
	this.name = other.getName();
}
 
Example 18
Source File: DataSourceTransactionManager.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Prepare the transactional {@code Connection} right after transaction begin.
 * <p>The default implementation executes a "SET TRANSACTION READ ONLY" statement
 * if the {@link #setEnforceReadOnly "enforceReadOnly"} flag is set to {@code true}
 * and the transaction definition indicates a read-only transaction.
 * <p>The "SET TRANSACTION READ ONLY" is understood by Oracle, MySQL and Postgres
 * and may work with other databases as well. If you'd like to adapt this treatment,
 * override this method accordingly.
 * @param con the transactional JDBC Connection
 * @param definition the current transaction definition
 * @throws SQLException if thrown by JDBC API
 * @since 4.3.7
 * @see #setEnforceReadOnly
 */
protected void prepareTransactionalConnection(Connection con, TransactionDefinition definition)
		throws SQLException {

	if (isEnforceReadOnly() && definition.isReadOnly()) {
		Statement stmt = con.createStatement();
		try {
			stmt.executeUpdate("SET TRANSACTION READ ONLY");
		}
		finally {
			stmt.close();
		}
	}
}
 
Example 19
Source File: DefaultTransactionDefinition.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Copy constructor. Definition can be modified through bean property setters.
 * @see #setPropagationBehavior
 * @see #setIsolationLevel
 * @see #setTimeout
 * @see #setReadOnly
 * @see #setName
 */
public DefaultTransactionDefinition(TransactionDefinition other) {
	this.propagationBehavior = other.getPropagationBehavior();
	this.isolationLevel = other.getIsolationLevel();
	this.timeout = other.getTimeout();
	this.readOnly = other.isReadOnly();
	this.name = other.getName();
}
 
Example 20
Source File: DefaultTransactionDefinition.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Copy constructor. Definition can be modified through bean property setters.
 * @see #setPropagationBehavior
 * @see #setIsolationLevel
 * @see #setTimeout
 * @see #setReadOnly
 * @see #setName
 */
public DefaultTransactionDefinition(TransactionDefinition other) {
	this.propagationBehavior = other.getPropagationBehavior();
	this.isolationLevel = other.getIsolationLevel();
	this.timeout = other.getTimeout();
	this.readOnly = other.isReadOnly();
	this.name = other.getName();
}