I have read this @Transactional method called from another method doesn't obtain a transaction and learned that we can't call a @Transactional method from another method in the same class. I'm wondering if the following code works. I know that we can't put @Transactional on doSomething
and have doSomethingTransactionally
to call it directly, so I created a utility method that has @Transactional annotation in another class which takes in a function and execute it. The goal is to keep all the logic in the same class. If the following code does not work, is there a way to achieve this goal?
@Component
class A {
@Autowired
B b;
public String doSomethingTransactionally() {
return b.transactionalHelper(this::doSomething);
}
public String doSomething() {
// a bunch of db operations
}
}
@Component
class B {
@Transactional
public T transactionalHelper(Supplier<T> supplier) {
return supplier.get();
}
}