TheOpenCloudEngine / uEngine5-base

uEngine5 BPMS that totally re-written in Microservices architecture. uEngine5 can act as not only a conventional Workflow or BPMS but also as a REST api orchestrator or a BPaaS (Business process as a service) of members of OCE's MSA components.
MIT License
10 stars 13 forks source link

JPAProcessInstance listening beforeCommit event from Spring Transaction Manager #21

Open jinyoung opened 6 years ago

jinyoung commented 6 years ago

To store all the changes during the JPAProcessInstance's instance is modified in a transaction, we need to capture the moment that all the transaction has been committed by the Spring container (transaction manager).

jinyoung commented 6 years ago

use this : https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2

jinyoung commented 6 years ago

Following is implemented in JPAProcessInstance to issue an event

    @Autowired
    ApplicationEventPublisher applicationEventPublisher; //TODO see the DefinitionService.beforeProcessInstanceCommit() and move to here someday

    @PostConstruct
    public void init() throws Exception {

        if(isNewInstance()) { //if new instance, create one
            processInstanceRepository.save(getProcessInstanceEntity());
            setInstanceId(String.valueOf(getProcessInstanceEntity().getInstId()));
        }else{ //else, load the instance
            setProcessInstanceEntity(processInstanceRepository.findOne(Long.valueOf(getInstanceId())));

            IResource resource = new DefaultResource("instances/" + getInstanceId());
            Map variables = (Map) resourceManager.getObject(resource);

            setVariables(variables);
        }

        applicationEventPublisher.publishEvent(new ProcessInstanceChangeEvent(this));
    }

Following is a event listener implementation in DefinitionService

    //TODO: must moved to InstanceService later.
    @TransactionalEventListener(fallbackExecution=true, phase = TransactionPhase.BEFORE_COMMIT)
    public void beforeProcessInstanceCommit(ChangeEvent<ProcessInstance> changeEvent) throws Exception {

        ProcessInstance instance = changeEvent.getObject();

        IResource resource = new DefaultResource("instances/" + instance.getInstanceId());
        resourceManager.save(resource, ((DefaultProcessInstance)instance).getVariables());
    }