Class A{
@transactional public Void methodA(){
methodB();
int i=10/0;
}
@transactional public void methodB(){
session.save(student)
}
Here there is an exception in methodA but it is not rolling back and inserting student data.why?
}
Class A{
@transactional public Void methodA(){
methodB();
int i=10/0;
}
@transactional public void methodB(){
session.save(student)
}
Here there is an exception in methodA but it is not rolling back and inserting student data.why?
}
By default, @Transactional rolls back on runtime exceptions.
You need to use rollbackFor().
@Transactional(rollbackFor = {MyException.class})
Method marked with @Transactional
has to be public
.
This is documented in Spring Manual chapter 10.5.6:
Method visibility and
@Transactional
When using proxies, you should apply the
@Transactional
annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the@Transactional
annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.
Beacuse A and B separate transactions !
When you call a method without @Transactional
within a transaction block, the parent transaction will continue to the new method. It will use the same connection from the parent method(with @Transactional
) and any exception caused in the called method(without @Transactional
will cause the transaction to rollback as configured in the transaction definition.
If you call a method with a @Transactional
annotation from a method with @Transactional
within the same instance, then the called methods transactional behavior will not have any impact on the transaction. But if you call a method with a transaction definition from another method with a transaction definition, and they are in different instances, then the code in the called method will follow the transaction definitions given in the called method.
You can find more details in the section Declarative transaction management of spring transaction documentation.
Spring declarative transaction model uses AOP proxy. so the AOP proxy is responsible for creation of the transactions. The AOP proxy will be active only if the methods with in the instance are called from out side the instance.
The answer depends on what you already know.
Do you know how Spring works when you add a @Transactional annotation? Ans: It does so by creating a proxy class for the class which has annotated methods.
Do you know how Spring Proxy object works when one method in the proxied class calls another method in the same proxied class? Ans: Sprig is not able to handle this scenario implicitly. Any annotation on the called method would be ignored (since the call happens on 'this' rather than on the Proxy) You need to switch to AspectJ to handle such scenario's
If you really like to understand this behavior I recommend reading this section of the Spring documentation.