Accessing current transaction in Spring

Posted on 16-05-2013 17:16 by graham
This tutorial shows how to programmatically access and manipulate a current transaction in Spring. The transaction accessed is created in a declarative way.

Simple declarative transaction


Let's say we have a transactional method that looks something like this:
SettingService.java
@Service
public class SettingsService
{
@Transactional(readOnly = true)
public String getSetting (String name, EnvData envData) throws KolmuException
{
// do something
}
}

Now, within that transactional method, we suddenly decide we want to get access to the current Spring transaction and rollback it. To do this, we need to inject the current transaction manager to our service class, and using it obtain access to the transaction:
SettingService.java
@Service
public class GlobalSettingsService
{
// inject JTA tranaction manager, or any other tx manager you are using
@Inject
JtaTransactionManager transactionManager;

@Transactional(readOnly = true)
public String getSetting (String name, EnvData envData) throws KolmuException
{
// do something

// rollback the transaction
transactionManager.getUserTransaction().rollback();
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems