JPA query.getResultList()?
我使用JPA 1.0:
Query query; query = em.createNamedQuery("getThresholdParameters"); query.setParameter(1, Integer.parseInt(circleId)); List resultList = new ArrayList(); resultList = query.getResultList();
在这里我得到List
,因此我必须键入将行的所有参数转换为它们各自的类型,这很麻烦。
在JPA 2.0中,有TypedQuery返回类型为1的实体对象指定。
但是当我使用JPA 1时,我无法使用它。
如何获得结果作为我想要的类型的实体对象?
编辑:查询
@Entity @Table(name="GMA_THRESHOLD_PARAMETERS") @NamedQuery( name = "getThresholdParameters", query = "select gmaTh.minNumberOc, gmaTh.minDurationOc, gmaTh.maxNumberIc, gmaTh.maxDurationIc, gmaTh.maxNumberCellId," + "gmaTh.distinctBnumberRatio, gmaTh.minPercentDistinctBnumber from GmaThresholdParameter gmaTh " + "where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3 " )
您的查询选择了许多字段。 这样的查询总是返回Object数组的列表。 如果您想要一个包含GmaThresholdParameter实体实例的列表,那么查询应该是
select gmaTh from GmaThresholdParameter gmaTh where gmaTh.id.circleId=?1 AND gmaTh.id.tspId=?2 AND gmaTh.id.flag=?3
然后,获取实体列表的代码将是
List resultList = query.getResultList();
您将从编译器获得类型安全警告,您可以忽略。
我不能回复这个评论,所以我会继续做一个答案。
List
而且,由于您将getResultList()返回的列表分配给您自己的空ArrayList所使用的相同变量,因此您的应用程序将失去与您自己的空ArrayList的任何连接,Java会将其作为垃圾收集。 基本上你创造它绝对没有目的。
JB Nizet发布的内容就足够了。
List resultList = query.getResultList();
我当时使用JPA 1时做了类似的事情:
final Collection typedResult = new ArrayList for(final Object result : query.getResultList()) { typedResult.add((YourType) result); } return typedResult;
List result= query.getResultList(); for( GmaThresholdParamerter res : result) { System.out.println("" +res.getMinNumberOc()); System.out.println("" +res.getMinDurationOc()); }