我有以下返回列表的 Criteria API 代码。
我想将其转换为 List<myClass>
我该怎么做?
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<ProductCatalogue> pc = cq.from(ProductCatalogue.class);
Root<ProductList> al = cq.from(ProductList.class);
.......
.......
.......
Predicate[] predicates = new Predicate[predicateList.size()];
predicateList.toArray(predicates);
criteriaQuery.where(predicates);
TypedQuery<Tuple> typedQuery = getEntityManager().cq(criteriaQuery);
List<Tuple> tuple = typedQuery.getResultList();
理想情况下我愿意
List<Employee> emp = tuple
但是上面导致了不兼容的类型错误,我不知道我该如何转换它。
最佳答案
如果您坚持使用元组查询,则必须手动转换实例。
如果myClass
是您应该使用的实体 CriteriaQuery< myClass>
正如 perissf 建议的那样,否则您可以使用“构造函数表达式”直接从选择中创建实例,例如:
select new com...myClass(c.id, c.price) FROM ProductList c WHERE c.....;
参见 this answer有关使用 Criteria API 创建此类查询的示例。
关于JPA 将 List<Tuple> 转换为 List<myClass>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33734860/