Although I had annoted my method as @Transactional no transaction was started. Situation was the following:
applicationContext.xml
... <!-- Enable @Transactional support --> <tx:annotation-driven transaction-manager="transactionManager" /> ...
Test.java
class Test {
public static void main(String args[]) throws Exception {
...
Test test = factory.getBean("test");
test.run();
}
public void run() {
// code before transaction
runTransactional();
// code after transaction
}
@Transactional
public void runTransactional() {
// code in transaction
}
}
I found the reason in a little hint in the Spring Documenation (Using @Transactional):
Note: In proxy mode (which is the default), only ‘external’ method calls coming in through the proxy will be intercepted. This means that ‘self-invocation’, i.e. a method within the target object calling some other method of the target object, won’t lead to an actual transaction at runtime even if the invoked method is marked with
@Transactional!
So the solution is either to use aspectj instead of proxy-mode or to make an ‘external’ method call. I used the second. So I head to move the code from run() to main() so that I have an ‘external’ method call to runTransactional().
Test.java
class Test {
public static void main(String args[]) throws Exception {
...
Test test = factory.getBean("test");
// code before transaction
test.runTransactional();
// code after transaction
}
@Transactional
public void runTransactional() {
// code in transaction
}
}