0

It has probably already been asked, but I didn't find the answer so I'm asking it.

If I have this pattern:

@Transactional
private methodA(List<Long> ids) {
   // Call to DB
}

public methodB(List<Long> ids) {
   // Operations that doesn't require DB calls
   this.methodA(ids);
   // Operations that doesn't require DB calls
}

Should Method B be transactional? And if not, will it make shorter the transaction duration?

rkosegi
  • 14,165
  • 5
  • 50
  • 83
Paul Serre
  • 457
  • 3
  • 11
  • The annotation [won't work](https://stackoverflow.com/q/4396284/2541560) on a private method. – Kayaman Nov 24 '21 at 20:28
  • `methodB` must be transactional, as it's calling `methodA` locally as opposed to via a transaction proxy. `@Transactional private methodA` is meaningless. You will have to call `@Transactional public methodB` – Ori Dar Nov 24 '21 at 20:28
  • *A method who call a transactional method has to be transactional?* no, otherwise everything before should be transactional – fantaghirocco Nov 24 '21 at 20:38

1 Answers1

3

The transaction is implemented through a proxy. Calls from within the object (such as code within methodB) don't go through the proxy.

You can have one nontransactional service, and one transactional service, and inject the transactional service into the other, so you can call a transactional method from the nontransactional service and go through the proxy. That way you can keep the boundaries you want on your transaction.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276