Using @ElementCollection in CriteriaQuery (or Querying over the content of an @ElementCollection)

可紊 提交于 2019-12-05 07:49:19

I would use following CriteriaQuery syntax for doing the same thing.

EntityManager em = entityManagerFactory.createEntityManager();

final List<ReportStatus> reportStatuses = new ArrayList<ReportStatus>();
reportStatuses.add(ReportStatus.FAILED);

final CriteriaBuilder builder = em.getCriteriaBuilder();

final CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
final Root<Work> _work = criteriaQuery.from(Work.class);

/*final ListJoin<Work, ReportStatus> status = _work.joinList("reportStatuses");
final Predicate predicate = status.in(reportStatuses);
criteriaQuery.where(predicate);*/

final Expression<List<ReportStatus>> _status = _work.get(Work_.reportStatuses);
_status.in(reportStatuses);

criteriaQuery.select(_work.get(Work_.id));

List<Long> list =  em.createQuery(criteriaQuery).getResultList();

UPDATE

Thanks, but we do not use the generated metamodel. So unfortunately I can't try with your answer. :(

If you don't use Metamodel, just replace _work.get(Work_.reportStatuses) with _work.get("reportStatuses"). It'll work. :)

user904084

You can create this HQL.

String query = "SELECT w.id FROM Work w, IN(w.reportStatuses) s WHERE s = :rs";
return this.entityManager.createQuery(query).setParameter("rs", ReportStatus.FAILED).getResultList();

I'm confused. The call to in(..) returns a predicate but doesn't seem to actually enforce it (it doesn't seem to be integrated into the query—at least for me it returned all members of the root whether or not their collections intersected with reportStatuses. The debug log shows the simple query select distinct work0_.id as id18_ from Work work0_).

Also, why bother putting reportStatuses in a list if the caller is only interested in those matching one value? How would you do the query w/ just using ReportStatus.FAILED instead of constructing a list for it?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!