Alao
Alao

Reputation: 400

Restore Spring State Machine from Database

I have been following the data persist examples outlined in the spring docs

When I acquire a state machine it doesn't pull it from the database but checks in memory. I see records being written but I just can't restore them. Here is my configuration I have defined the StateRepository and the

private final StateRepository<? extends RepositoryState> stateRepository;
private final TransitionRepository<? extends RepositoryTransition> transitionRepository;
private final StateMachineRuntimePersister<LoanEventStatus, LoanEventAction, String> stateMachineRuntimePersister;

Here are my beans based on the examples

@Bean
public StateMachineModelFactory<String, String> modelFactory() {
    return new RepositoryStateMachineModelFactory(stateRepository, transitionRepository);
}

@Bean
public DefaultStateMachineService<LoanEventStatus, LoanEventAction> stateMachineService(
        final StateMachineFactory<LoanEventStatus, LoanEventAction> stateMachineFactory,
        final StateMachinePersist<LoanEventStatus, LoanEventAction, String> stateMachinePersist) {

    return new DefaultStateMachineService<LoanEventStatus, LoanEventAction>(stateMachineFactory, stateMachinePersist);
}

@Bean
public StateMachinePersister<LoanEventStatus, LoanEventAction, String> persister(
        StateMachinePersist<LoanEventStatus, LoanEventAction, String> defaultPersist) {
    return new DefaultStateMachinePersister<>(defaultPersist);
}

I thought restoring them would be as simple as the following:

private final DefaultStateMachineService<LoanEventStatus, LoanEventAction> stateMachineService;
var stateMachine = stateMachineService.acquireStateMachine(id);

However, when I step into the DefaultStateMachineService I notice that the machines are empty. Shouldn't it restore when the application starts up or am i missing something

Upvotes: 0

Views: 1314

Answers (1)

Alao
Alao

Reputation: 400

So I realized the problem was with this method.

stateMachineService.hasStateMachine(id)

Looking at the code it only looks for state machines that are in memory. To get the ones that are in the database you need to use JpaRepositoryStateMachine

StateMachineRepository<JpaRepositoryStateMachine> stateMachineRepository;

Then do the following to test if there is a state machine in the database and create one if there is not.

Optional<JpaRepositoryStateMachine> instance = stateMachineRepository.findById(Integer.toString(loanDetailId));

if (instance.isPresent()){

StateMachine<State, Event> stateMachine = stateMachineService.acquireStateMachine(id);

Upvotes: 1

Related Questions