How do I change this Hibernate code with org.hibernate.criterion.Restrictions code to JPA. Is there any alternatives to Restrictions API?

514 views Asked by At

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
             */
            
    }

}
1

There are 1 answers

4
Desmond Stonie On

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.