Created
February 16, 2016 08:31
-
-
Save djechelon/170162fc1322a4d0f7c0 to your computer and use it in GitHub Desktop.
Transaction auto-closeable helper for Spring Transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Transaction extends AutoCloseable | |
{ | |
@Override | |
public void close() throws TransactionException; | |
public void rollback(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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