Reputation: 21
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
*/
}
}
Upvotes: 1
Views: 822
Reputation: 137
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 aCriteriaQuery
instance to do that.
Upvotes: 1