The following code will return one result based on 2 criteria:
- process entity attribute to be equal with process parameter
- state entity attribute to be equal with state parameter from function
Entity has these two attributes of type ENUM: process and state.
DB Table consist in a map between process and allowed states. Method findByType will return the correct entry based on one process and one state:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@Service public class JpaStateMachineDaoImpl implements JpaStateMachineDao { @PersistenceContext private EntityManager em; @Override public StateMachineEntity findByType(SmProcess process, SmState state) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<StateMachineEntity> cq = cb.createQuery(StateMachineEntity.class); Root<StateMachineEntity> model = cq.from(StateMachineEntity.class); List<Predicate> predicateList = new ArrayList<Predicate>(); Predicate processPredicate = cb.equal(model.get("process"), process.ordinal()); Predicate statePredicate = cb.equal(model.get("state"), state.ordinal()); predicateList.add(processPredicate); predicateList.add(statePredicate); Predicate[] predicates = new Predicate[predicateList.size()]; predicateList.toArray(predicates); cq.where(predicates); TypedQuery<StateMachineEntity> q = em.createQuery(cq); return q.getSingleResult(); } } |