Skip to content

Instantly share code, notes, and snippets.

@djechelon
Created February 16, 2016 08:31
Show Gist options
  • Save djechelon/170162fc1322a4d0f7c0 to your computer and use it in GitHub Desktop.
Save djechelon/170162fc1322a4d0f7c0 to your computer and use it in GitHub Desktop.
Transaction auto-closeable helper for Spring Transactions
public interface Transaction extends AutoCloseable
{
@Override
public void close() throws TransactionException;
public void rollback();
}
public final class TransactionUtils
{
private TransactionUtils()
{}
/**
* Helper method to get a simple-to-use, Entity-Framework styled helper for transactions.
* Use in try-with-resources blocks
*
* @param txManager
* Spring transaction manager
* @param definition
* Type of transaction. You can use any static helper here
* @return An {@link AutoCloseable} instance that wraps the transaction
* @throws TransactionException
* Just any exception normally thrown by {@link PlatformTransactionManager}
*/
public static Transaction openTransaction(final PlatformTransactionManager txManager, TransactionDefinition definition) throws TransactionException
{
final TransactionStatus status = txManager.getTransaction(definition);
return new Transaction()
{
private boolean isRollback = false;
@Override
public void rollback()
{
isRollback = true;
status.setRollbackOnly();
}
@Override
public void close() throws TransactionException
{
if (!isRollback)
txManager.commit(status);
else
txManager.rollback(status);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment