0
votes

I have a question about propagation in @Transactional annotation. I need to make two operations in one method and every should be in own transaction after which is making commit.

@Service
@Transactional
public class FakturaServiceImpl implements FakturaService {    

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) { 

      Platnosc plat = Optional.ofNullable(platDao.findOne(platnoscId))
             .orElseThrow(() -> new RecordNotExistsException("Platnosc", platnoscId));

      // here should be beginning of transaction
      Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);
      // commit
      // start new transaction
      rachotwMgr.dodajRachotwDlaZaliczekNaFakturze(faktId);
      // commit

      // ...
      return faktId;
    }

    @Override
    public Integer utworzFaktureZaliczkowaNaPodstPlatnosci(Platnosc plat) {
    // Here not starting new transaction, it's still Propagation.NOT_SUPPORTED
    rachotwMgr.naliczRachotwDlaRezerwacji(rezId, true); // this line is in new transaction
    // Continue in Propagation.NOT_SUPPORTED
    }
}

@Service
@Transactional
public class RachotwServiceImpl implements RachotwService {
    @Override
    @Transactional
    public List<Rachotw> dodajRachotwDlaZaliczekNaFakturze(@NotNull Integer fakturaId) {
    // Here starts new transaction..
    }
}

Is my idea with one method with Propagation.NOT_SUPPORTED and two methods inside with Propagation.REQUIRED right (after utworzFaktureZaliczkowaNaPodstPlatnosci() and dodajRachotwDlaZaliczekNaFakturze() should be commit)?

Why does utworzFaktureZaliczkowaNaPodstPlatnosci() which has Propagation.REQUIRED (by default) is not starting new transaction and dodajRachotwDlaZaliczekNaFakturze() and naliczRachotwDlaRezerwacji() starts new transaction. How to make utworzFaktureZaliczkowaNaPodstPlatnosci() to start a new transaction?

1

1 Answers

1
votes

This is pretty straight forward. By 'FakturaServiceImpl' class declaration the method utworzFaktureZaliczkowaNaPodstPlatnosci does support transaction but only if it will be called via bean declaration somewhere else:

@Inject
FakturaService service;


public void someMethod() {
   // Transaction will be here
   service.utworzFaktureZaliczkowaNaPodstPlatnosci(new Platnosc());
} 

But you are doing just a simple call to the method there is not transaction configuration involved.

@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public Integer przyjmijZaliczkeNaPodstPlatnosci(Integer platnoscId) { 
  .....

  // Simple method call
  Integer faktId = utworzFaktureZaliczkowaNaPodstPlatnosci(plat);

  // ...
  return faktId;
}