Public method with #Transactional calling private method - java

I have a few questions about #Transactional annotation. If I have an implementation similar as below:
#Transactional
public Interface ExampleRepo {
SampleClass createRecord();
}
public class RepoImpl implements ExampleRepo {
public SampleClass createRecord() {
return saveRecord();
}
private saveRecord() {
//Saving record to Database.
}
}
Will the transaction rollback as Spring will ignore if the #Transactional was called on a private method? But what if a public method annotated with #Transactional calls a private method that actually does the database operation.
Will this transaction be marked as rollback?

As per Spring Documentation
Spring recommends that you only annotate concrete classes (and methods
of concrete classes) with the #Transactional annotation, as opposed to
annotating interfaces. You certainly can place the #Transactional
annotation on an interface (or an interface method), but this works
only as you would expect it to if you are using interface-based
proxies. The fact that Java annotations are not inherited from
interfaces means that if you are using class-based proxies (
proxy-target-class="true") or the weaving-based aspect (
mode="aspectj"), then the transaction settings are not recognized by
the proxying and weaving infrastructure, and the object will not be
wrapped in a transactional proxy, which would be decidedly bad.
So, I would recommend to use #Transaction at method createRecord() level or RepoImpl class level.
All code within a transaction scope runs in that transaction. However, you can specify the behavior if a transactional method is run when a transaction context already exists.
When a method without #Transactional is called within a transaction block, the parent transaction will continue to exist for the new method. It will use the same connection from the parent method (method with #Transactional) and any exception caused in the called method (method without #Transactional) will cause the transaction to rollback as configured in the transaction definition.
Since this mechanism is based on proxies, 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.

Related

Spring #transactional not auto rolling back during unchecked exception

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.

how spring aop handle #Transactional with jdk proxy?

If one Service class has method with #Transactional, then spring will use proxy to handle it.
But if one Transactional method call another one
#Transactional
public FeedBackModel getOne() {
///..
return getTwo();
}
#Transactional
public FeedBackModel getTwo() {
return null;
}
like this.
if it is jdk proxy, then second #Transactional will not work.
But spring PROPAGATION will handle this correctly.
How it works?
If you are trying to commit a transaction in getTwo() which is called from getOne(), that will not work, not even when both are #Transactional. Refer to the documentation:
...please do take the Spring team's advice and only annotate concrete
classes (and the methods of concrete classes) with the #Transactional
annotation.
Note: Since this mechanism is based on proxies, 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!

Strange behaviour for chainned transactional annotation

I don't get how it works the transactional annotations of Spring. So I made the next test with no practical sense but I It shows my problem:
public class TransactionalTest {
public void noTransaction(){
required();
}
#Transactional(propagation = Propagation.SUPPORTS)
public void supports(){
required();
}
#Transactional(propagation = Propagation.REQUIRED)
public void transaction(){
required();
}
#Transactional(propagation = Propagation.REQUIRED)
public void required(){
mandatory();
}
#Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.MANDATORY)
public void mandatory(){
doSomething();
}
private void doSomething(){
//I don't feel like to do something.
}
}
Methods noTransaction, supports and transaction call to the same method: required but only the last one (transaction) works properly. The two others give me back the message No existing transaction found for transaction marked with propagation 'mandatory'.
In the real case, I have some non transactional methods which calls to transactional methods annotated with REQUIRED (It works fine). but if a non transactional method calls to a transactional method (annotated with REQUIRED) which it calls to another transactional method annoted with MANDATORY, it fails.
Why this behaviour and how can avoid it? I annotated annotate all the method which calls to a transaccional method just in case?
If you're using the default AOP method, Spring Proxy AOP, the advice is implemented by wrapping the annotated class with a proxy object that intercepts and advises the calls. When you use self-calls like this, you're bypassing the proxy, and the advice doesn't get applied.
If you really do need to have advice applied on self-calls, you need to use AspectJ AOP, which actually modifies the class in question instead of decorating it.

Seam #Transactional annotation not working?

I'm using the #Transactional annotation on a seam component similar to:
#Name( "myComponent" )
#AutoCreate
public class MyComponent
{
public void something() {
...
doWork();
}
...
#Transactional
protected void doWork() {
try {
log.debug( "transaction active: " + Transaction.instance().isActive() );
} catch (Exception ignore) {}
// some more stuff here that doesn't appear to be inside a transaction
}
}
In the "some more stuff" section, I'm modifying some Hibernate entities and then had a bug where an Exception was thrown. I noticed that the Exception wasn't causing the transaction to be rolled back (the modified entities were still modified in the db) so I added the "transaction active" logging. When this code executes, isActive() returns false.
Is there something I'm missing? Why isn't the transaction active?
In case it matters, I'm using the Seam component from inside another component that is using RESTEasy annotations to trigger my method calls.
I'm not familiar with how Seam works so my apologies in advance if this answer does not apply.
I noticed that the method that is #Transactional is protected. This implies to me that it is being called by another internal method.
With Spring's AOP, you mark the public methods with #Transactional which are wrapped and replaced with a transaction proxy. When an external class calls the public method, it is calling the proxy which forms the transaction. If the external class calls another public method that is not marked with #Transactional which then calls an internal method which is, there will be no transaction created because the proxy is not being called at all.
In Spring, even if you change your doWork() method to be public, the same problem would happen. No transaction because the proxy object is not being called. Method calls made inside of the class are not making calls to the proxy object.
A quick read of some documentation seems to indicate that, like Spring AOP, Seam is using CGLib proxying. The question is if it is able to proxy all methods -- even if they are called from within the proxied object. Sorry for wasting your time if this answer does not apply.

Spring #Transactional method - participating transaction

in one dao I have 2 #Transactional methods.
if i do not provide any explicit properties,
then what will happen, if
I run one method in the body of another?
Both methods will run within THE SAME ONE TRANSACTION?
Proxies in Spring AOP
When using Transactional, you're dealing with proxies of classes, so in this scenario:
#Transactional
public void doSomeThing(){ // calling this method targets a proxy
doSomeThingElse(); // this method targets the actual class, not the PROXY,
// so the transactional annotation has no effect
}
#Transactional
public void doSomeThingElse(){
}
you are calling the proxy from outside, but the second method call is made from inside the proxied object and therefor has no transactional support. So naturally, they run in the same transaction, no matter what the values of the #Transactional annotation in the second method are
so if you need separate transactions, you have to call
yourservice.doSomething();
yourservice.doSomethingElse();
from outside.
The whole scenario is explained pretty well in the chapter Spring AOP > Understanding AOP proxies, including this "solution":
Accessing the Current AOP Proxy object from the inside
public class SimplePojo implements Pojo {
public void foo() {
// this works, but... gah!
((Pojo) AopContext.currentProxy()).bar();
}
public void bar() {
// some logic...
}
}
The default value of the propagation attribute of #Transactional is REQUIRED, which means:
Support a current transaction, create a new one if none exists.
So yes - both methods will run in the same transaction.
But one important advice: don't make your DAO transactional. The services should be transactional, not the DAO.
Spring doc
one note:
In proxy mode (which is the default),
only external method calls coming in
through the proxy are intercepted.
This means that self-invocation, in
effect, a method within the target
object calling another method of the
target object, will not lead to an
actual transaction at runtime even if
the invoked method is marked with
#Transactional.

Categories