Search code examples
javahibernatespring-bootcamunda

why my services doen't write in database when calling them from components?


I'm creating a delegate expression for a Camunda process the workflow works perfect but when it executes the delegate my services creates the objects and doesn't write them into the database. this is the code:

@Component
public class CreateNewROAction implements JavaDelegate {

    private final ROactionService rOactionService;
    private final RiskService riskService;
    private Logger logger = LoggerFactory.getLogger(CreateNewROAction.class);
    public CreateNewROAction(ROactionService rOactionService, RiskService riskService) {
    this.rOactionService = rOactionService;
    this.riskService = riskService;
}

    @Override
    public void execute(DelegateExecution delegateExecution) throws Exception {

        String processInstanceId = delegateExecution.getProcessInstanceId();
        String riskId = delegateExecution.getVariable("riskId").toString();
        Risk risk = riskService.findById(Long.parseLong(riskId));
        ROaction rOaction = new ROaction();
        rOaction.setProcessInstanceId(processInstanceId);
        rOaction = rOactionService.save(rOaction);
        logger.info("roAction object: " + rOaction.toString());
        risk.setAction(rOaction);
        risk = riskService.update(risk, risk.getId());
        logger.info("risk object: " + risk.toString());
        delegateExecution.setVariable("id", rOaction.getId());

    }
}

the loggers indicate the result that I expected:

roAction object: ROaction(id=4, description=null, status=null, responsible=null, deadline=null, AchievementDate=null, effectivenessEvaluationDate=null, effectivenessEvaluation=null, processInstanceId=819, createdAt=Wed Jul 03 15:08:19 CET 2019, updatedAt=Wed Jul 03 15:08:19 CET 2019)
risk object: Risk(id=4, description=null, probability=0, impact=0, cause=null, consequence=null, createdAt=2019-07-03 15:07:04.975, updatedAt=2019-07-03 15:07:04.975, processes=[], action=ROaction(id=4, description=null, status=null, responsible=null, deadline=null, AchievementDate=null, effectivenessEvaluationDate=null, effectivenessEvaluation=null, processInstanceId=819, createdAt=Wed Jul 03 15:08:19 CET 2019, updatedAt=Wed Jul 03 15:08:19 CET 2019), processInstanceId=801)

but the database is empty.
Notes:
1. I had to change the entity's id to @GeneratedValue(strategy = GenerationType.SEQUENCE) because before that the service returns a null Id from save() function
2. the services work fine from controllers


Solution

  • The solution is to not call the service methods directly but to call them through private methods annotated by @Transactional. The reason is that Hibernate open connection with the database in the first call and then close it. The component has just one connexion to the Database so it can't access it after the first call. @Transactional open a new connection with the database for the method.