简体   繁体   English

java jpql与众不同,并检索许多字段

[英]java jpql distinct and retrieve many fields

I have this query in mysql: 我在mysql中有以下查询:

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

I wrote this code: 我写了这段代码:

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

I tried to cast the results into an HashMap<String, String> but jpql return a ClassCastException from Object to HashMap. 我试图将结果转换为HashMap<String, String>但是jpql从Object到HashMap返回ClassCastException

How can I retrieve these results? 如何获取这些结果? Should I create a custom class that contains the three fields? 是否应该创建一个包含三个字段的自定义类? If it is correct, what will return month and year? 如果正确,则将返回月份和年份?

PS: I'm using jdk 1.8, jpa 2.1, mysql and eclipselink PS:我正在使用jdk 1.8,jpa 2.1,mysql和eclipselink

You can retrieve the result by typing the expected result of the query. 您可以通过键入查询的预期结果来检索结果。 A generic way is to indicate that you want retrieve a List of Object[]. 一种通用方法是指示您要检索Object []的列表。
The List corresponds to each line returned by the request and the Object[] contains values returned by each row. 该列表对应于请求返回的每一行,而Object []包含每一行返回的值。 The object are ordered in the same order that values returned. 对象的顺序与返回值的顺序相同。

Alias are not needed because not used in the result. 不需要别名,因为结果中未使用别名。 So I remove them. 所以我删除了它们。
And you should not query from the table name otherwise it looks like a SQL native query (which is possible to do with JPA) but you should rather specify in the FROM clause the entity name. 而且,您不应该从表名进行查询,否则它看起来像是SQL本机查询(可以通过JPA进行查询),而应该在FROM子句中指定实体名称。 So I modified it for the principle. 所以我修改了它的原理。
Here the modified query with the handling of the result : 这是修改后的查询以及结果处理:

 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]);
  }

It is not the most beautiful way to retrieve the data but if it matches to your need, you don't need to do more. 这不是检索数据的最漂亮方法,但是如果它符合您的需求,则您无需做更多的事情。

Should I create a custom class that contains the three field? 我是否应该创建一个包含三个字段的自定义类?

it's practical to do it if this custom class is reused elsewhere. 如果将此自定义类在其他地方重用,则可以这样做。 Otherwise, it looks like more a overhead. 否则,看起来更多的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM