How to implement a state template in a JPA domain model

I want to implement a state design template in JPA. The way I do it now is outlined in this post.

The author uses an enumeration containing all available implementations, instead of creating an abstract class / interface to abstract the state and write the implementation for each state. I find this approach very useful, since enumerations can be easily serialized in JPA, and you can save the current state of your object without extra effort. I also nested the state interface and all state classes in enum, making them private, as they are implementation specific and should not be visible to any client. Here is an example enumeration code:

public enum State { STATE_A(new StateA()), STATE_B(new StateB()); private final StateTransition state; private State(StateTransition state) { this.state = state; } void transitionA(Context ctx) { state.transitionA(ctx); } void transitionB(Context ctx) { state.transitionB(ctx); } private interface StateTransition { void transitionA(Context ctx); void transitionB(Context ctx); } private static class StateA implements StateTransition { @Override public void transitionA(Context ctx) { // do something ctx.setState(STATE_B); } @Override public void transitionB(Context ctx) { // do something ctx.setState(STATE_A); } } private static class StateB implements StateTransition { @Override public void transitionA(Context ctx) { throw new IllegalStateException("transition not allowed"); } @Override public void transitionB(Context ctx) { // do something ctx.setState(STATE_A); } } } 

I would like to share this with you and talk about it. Do you find this helpful? How to implement a state design pattern in a JPA domain model?

Thanks Theo

+4
source share
1 answer

Well, this is an old question, but for the sake of those who can search for archives - I used the spring state machine with enumerations (instead of strings).

As for transition processing, there are annotations that allow you to call functions on a transition.

1.1.0.RELEASE provides a default mechanism for saving state using StateMachineContext persistent state and an alternative that uses preserve recipe .

Now, referring to JPA - it is possible that the Entity Listener will initialize statemachine to postload (@Postload), I think this is not a good way.

0
source

All Articles