Basic settings are all fine now and I started to try transactions. Struts+Spring+Hibernate annotation transaction manager. This is the sample code in Action, will call a service class:
userService.addUser();
Here is the addUser()
method in service class:
@Transactional(value="deu" )
public void addUser() {
userDao.addUser();
this.addUser2();
}
First, I called addUser
in userDao, which will insert a user. Second, I called addUser2
in another method in this service class.
@Transactional(value="deu" , propagation=Propagation.REQUIRES_NEW )
public void addUser2() {
//should be a new transaction and will not affect the previous one.
//this one will fail but should not affect the previous one.
userDao.addUserFail();
}
And this one will failed due to null PK. I suppose the second call (addUser2
) will fail but will not affect the previous one. However, the user is not inserted.
If I only call:
@Transactional(value="deu" )
public void addUser() {
userDao.addUser();
//this.addUser2();
}
It is working, meaning basic settings like database is not wrong.
Any idea?
Spring's declarative transaction handling works using AOP proxies. When you get a tranasactional bean, you in fact get a proxy which wraps your bean instance, intercepts the method call, starts a transaction if necessary, then calls the actual bean's method, then commits or rollbacks the transaction if necessary.
But you're calling a method of your bean from another method inside the same bean, so the proxy is bypassed, and can't apply any transactional behavior.
Put the method in another bean, or use AspectJ, which instruments the byte code and can intercept intra-bean method calls.
For a more detailed explanation, see the Spring documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With