Issue
Recently, I've been working with Spring boot + spring data jpa + hibernate. I faced one problem with spring transactions. Here is my service class and two questions:
@Transactional
@Service
class MyService {
@Autowired
private MyRepository myRep;
public void method_A() {
try {
method_C();
.....
method_B();
} catch(Exception e) {}
}
public void method_B() {
Entity e = new Entity();
e.set(...);
myRep.save(e);
}
public void method_C() throws Exception {
....
}
}
1.If method method_C()
throws an Exception and I want to catch it and log it, the transaction is not rollbacked in method method_B()
, because the Exception does not reach Spring framework. So how should I do in order to catch Exceptions from method_C()
and at the same time do not lose capability of method method_B()
be rollbacked?
2.Consider new method method_A()
.
public void method_A() {
for(...) {
...
...
method_B();
}
}
I want invoke method_B()
in a loop. If an exception occurs in a method_B()
I want transaction of method_B()
be rollbacked but method_A()
should not exit and the loop should continue excuting. How can I achieve this?
Solution
I solved my 2 problems this way: created another @Service
class and moved method_B()
into it. I've annotated this class as @Transactional
. Now the method method_A()
looks like this:
public void method_A() {
for(...) {
...
try {
anotherService.method_B();
} catch (Exception e) {
logger.error(...);
}
}
}
If RuntimeException
occurs in the method_B()
method, the exception is propertly logged, transaction of method_B()
is rollbacked and the loop continuous. Thanks everybody for responses.
Answered By - polis