mercredi 25 février 2015

Spring TransactionTemplate with nested calls

I've a application with a complex transaction scenario.


I've a task that do many transactions. I try to simplify it to show you the concept:


I've a main task that open a transaction for every appointment readed from the db:



@Component
public class MainTask {

@Inject
TransactionTemplate transactionTemplate;

@Scheduled(cron = "*/30 * * * * ?")
public void execute() {

List<Long> appointments = new ArrayList<Long>();

transactionTemplate.execute(status -> {
try {
appointments= communicationClass.loadAppointments();

} catch (Exception e) {
log.error("", e);
status.setRollbackOnly();
}
return null;
});

appointmens.parallelStream().forEach(id -> {
transactionTemplate.execute(status -> {
try {

communicationClass.evaluateSms(id);

} catch (Exception e) {
log.error("", e);
status.setRollbackOnly();
}
return null;
});


This is the CommunicationClass:



@Component
public class CommunicationClass{

@PersistenceContext
EntityManager entityManager;

public List<Long> loadAppointments() {
//CALL A SERVICE TO GET THE LIST OF APPOINTMENTS
return appointmentService.loadAppointments();
}


public void evaluateSms(long idAppuntamento) {
boolean orarioSms = templateServiceImpl.canInviaSms(template, appuntamento);

//REMOTE CALL
boolean esitoInvio = inviaSmsGateway(appuntamento, sms, template);
if (esitoInvio == false)
throw new RuntimeException("Rollback of the entire transaction");
}


This is the TemplateServiceImpl class used before:



@Service
@Transactional
public class TemplateServiceImpl {

public boolean canInviaSms(Template template, IHasComunicazioni oggetto) {
//DO SOMETHING WITH OBJECTS RECEIVED
}


My questions are:



  1. The transaction opened from the transactionTemplate is preserved also when there is a call to communicationClass and later to the service (annotated with @Transactional)?

  2. The RuntimeException thrown in evaluateSms() should rollback the entire transaction opened inside the for(), right?

  3. if is thrown an exception inside the method canInviaSms() of TemplateServiceImpl is rolledback the entire transaction?


Thanks


Aucun commentaire:

Enregistrer un commentaire