Reputation: 609
I'm creating an project that needs a FSM and i choose Spring State Machine to help me solve the problem. I'm using JPA and trying to figure out how to start the state machine based on my current state retrieving the state from an JPA repository. I found on documentation this approach: state machine persist
But i'm confusing about this approach too: persisting state machine
I'm not trying to persist all state machine configuration, but only start and send events based on my entity status. but in both cases i don't know how to put jpa repository to find my current state.
Now i'm trying this approach:
class StateMachineAdapter<S, E, T> {
lateinit var stateMachineFactory: StateMachineFactory<S, E>
lateinit var persister: StateMachinePersister<S, E, T>
fun stateMachineRestore(contextObject: T): StateMachine<S, E> {
val stateMachine: StateMachine<S, E> = stateMachineFactory.getStateMachine()
return persister.restore(stateMachine, contextObject)
}
fun persist(stateMachine: StateMachine<S, E>, contestation: T) {
persister.persist(stateMachine, contestation)
}
fun create(): StateMachine<S, E> {
val stateMachine: StateMachine<S, E> = stateMachineFactory.getStateMachine()
stateMachine.start()
return stateMachine
}
}
I found this piece of code in Spring documentation, and i thought it could be replaced with JpaRepository:
public void change(int order, String event) {
Order o = jdbcTemplate.queryForObject("select id, state from orders where id = ?", new Object[] { order },
new RowMapper<Order>() {
public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Order(rs.getInt("id"), rs.getString("state"));
}
});
handler.handleEventWithState(MessageBuilder.withPayload(event).setHeader("order", order).build(), o.state);
}
Upvotes: 1
Views: 2236
Reputation: 2646
This indeed has been quite awkward to do using existing functionality as there is a lot of moving parts as you've probably seen from samples and docs.
I'm currently working to overhaul things around this in next 1.2.8 release to make persisting easier. If you're willing to use snapshots(in 1.2.x branch) until 1.2.8 is out, then start by checking new sample datajpapersist sample. Based on same concepts as storing configs but with new persist classes in spring-statemachine-data. Also issues around this 1.2.8 gh issues.
It'd be good to get some feedback on this.
Upvotes: 2