java jpql 不同并检索许多字段

java jpql distinct and retrieve many fields

我在 mysql 中有这个查询:

select distinct Month(date), year(date), field3
from table

我写了这段代码:

Query q = em.createQuery(
   "select distinct function('month',t.date) as month, function('year',t.date) as year, field3 as field3 from Table t"
);

我试图将结果转换为 HashMap<String, String> 但 jpql return 一个 ClassCastException 从对象到 HashMap。

如何检索这些结果? 我应该创建一个包含这三个字段的自定义 class 吗? 如果正确,return年月是什么?

P.S.: 我正在使用 jdk 1.8、jpa 2.1、mysql 和 eclipselink

您可以通过键入查询的预期结果来检索结果。 一种通用的方法是指示您要检索 Object[].
的列表 List 对应于请求返回的每一行,而 Object[] 包含每一行返回的值。对象的排序顺序与返回值的顺序相同。

不需要别名,因为结果中没有使用。所以我删除它们。
并且您不应该从 table 名称查询,否则它看起来像 SQL 本机查询(这可能与 JPA 相关),但您应该在 FROM 子句中指定实体名称。所以为了原理我修改了一下。
这里修改后的查询与结果的处理:

 TypedQuery<Object[]> query = em.createQuery(
      "select distinct function('month',t.date) ,
       function('year',t.date) , field3 from YourEntity t", Object[].class);
  List<Object[]> results = query.getResultList();
  for (Object[] result : results) {
      System.out.println("month: " + result[0] + ", year: " + result[1]
      + ", field3:"+  result[2]);
  }

这不是最漂亮的数据检索方式,但如果它符合您的需要,您不需要做更多的事情。

Should I create a custom class that contains the three field?

如果这个习惯 class 在别处被重复使用,这样做是可行的。否则,它看起来更像是一个开销。