0

Does anyone know how to change this to JPA? and if there are any alternatives for the org.hibernate.criterion.Restrictions API? Thank you!

public void initShowAFilterCriteria (Criteria crit, ShowingAFilter filter, Object user) {

    if(filter == null) {
        return; // do nothing
    }
    switch (filter) {
        case ALL;
            break; // do nothing
        case MINE;
            crit.add(Restrictions.or(Restrictions.isNull("something"),
                    Restrictions.eq("something.id", user.getId())));
            crit.add(Restrictions.eq(Object.A_CONSTANT, "N"));
            break;
            /**
             * the rest of the switch statments are in a similar construct
             */
            
    }

}
dariosicily
  • 4,239
  • 2
  • 11
  • 17

1 Answers1

0

You can use CriteriaBuilder and CriteriaQuery interface instead of Hibernate's Restrictions and Criteria, just like follows:

public CriteriaQuery<User> initShowAFilterCriteria (CriteriaBuilder cb, ShowingAFilter filter, Object user) {

    CriteriaQuery<User> cq = cb.createQuery(User.class);
    Root<User> root = cq.from(User.class);

    if(filter == null) {
        return; // do nothing
    }
    switch (filter) {
        case ALL;
            break; // do nothing
        case MINE;
            cq.select(root)
                .where(cb.or(
                    cb.isNotNull(root.get("something")), 
                    cb.equal(root.get("something.id"), user.getId())))
                .where(cb.equal(root.get(Object.A_CONSTANT), "N"));
            break;
            /**
             * the rest of the switch statments are in a similar construct
             */
    }
    return cq;
}

Attention: Unlike Hibernate’s Criteria can perform a query directly, using JPA's API, you need return a CriteriaQuery instance to do that.

  • Thank you Desmond, but what if I already declared those variables outside the method initShowingFilterCriteria() and this method just built on it. For example: – Yaw_Osei Jul 07 '21 at 14:28
  • What do you mean *those variables*? – Desmond Stonie Jul 08 '21 at 01:28
  • I mean't what if this line of code had already been declared outside the method: CriteriaQuery cq = cb.createQuery(User.class); Root root = cq.from(User.class); – Yaw_Osei Jul 08 '21 at 14:00
  • You just need to pass those variables(`cb`, `cq`, `root`) as arguments of the method initShowingFilterCriteria. – Desmond Stonie Jul 09 '21 at 01:16