public enum ReportStatus {
SUCCCEED, FAILED;
}
public class Work {
@ElementCollection
@Enumerated(EnumType.STRING)
List<ReportStatus> reportStatuses;
}
Given the following structure, I would like to execute a query to find all the work filtered by reportStatuses. It works fine with the following hql syntax:
public List<Long> queryHQL() {
final String query = "SELECT w.id FROM Work w JOIN w.reportStatuses s WHERE s in (:rs)";
final List<ReportStatus> reportStatuses = new ArrayList<ReportStatus>();
reportStatuses.add(ReportStatus.FAILED);
return this.entityManager.createQuery(query).setParameter("rs", reportStatuses).getResultList();
}
But I would like to use API criteria (jpa2) and cannot figure out how to do this. Here is my closest attempt, I think:
public List<Long> query() {
final List<ReportStatus> reportStatuses = new ArrayList<ReportStatus>();
reportStatuses.add(ReportStatus.FAILED);
final CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
final Root<Work> workModel = criteriaQuery.from(Work.class);
final ListJoin<Work, ReportStatus> status = workModel.joinList("reportStatuses");
final Predicate predicate = status.in(reportStatuses);
criteriaQuery.where(predicate);
criteriaQuery.select(workModel.<Long> get("id"));
return this.entityManager.createQuery(criteriaQuery).getResultList();
}
I also tried with the hibernate API, but as jpa2 I could not find the correct syntax.
source
share