简体   繁体   English

我如何仅从JPQL中的日期时间字段按日期分组

[英]How do i group by date only from date time field in JPQL

For mysql I wrote a query like 对于mysql我写了一个类似的查询

SELECT * FROM mytable GROUP BY DATE(dateTimeField)

But i can't use the DATE() function in JPQL. 但我不能在JPQL中使用DATE()函数。 Anyone have an idea how to resolve this problem? 任何人都知道如何解决这个问题?

If You use Hibernate under the hood you can try : 如果您在引擎盖下使用Hibernate,您可以尝试:

  1. Create your own dialect with custom function 使用自定义功能创建自己的方言

     public class CustomPostgresqlDialect extends PostgreSQLDialect { public CustomPostgresqlDialect() { super(); registerFunction("truncate_date", new SQLFunctionTemplate( StandardBasicTypes.TIMESTAMP, "DATE(?1)" )); } } 
  2. Register Your dialect in persistence.xml persistence.xml注册您的方言

     <property name="hibernate.dialect" value="my.own.CustomPostgresqlDialect"/> 
  3. Use your function in JPQL. 在JPQL中使用您的函数。

     select p from Post p group by truncate_date(p.dateCreated) 

For Hibernate: 对于Hibernate:

Suggestion 1: 建议1:

Use cast(dateTimeField as date) . 使用cast(dateTimeField as date) See here . 看到这里

Suggestion 2: 建议2:

You can try to concatenate year , month and year HQL expressions . 您可以尝试连接yearmonthyear HQL表达式

Take a look at line 360 of this testcase . 看看这个测试用例的第360行。

str(year(current_date))||'-'||str(month(current_date))||'-'||str(day(current_date))

But take the time to see the generated SQL, it may (and probably will be) ugly and slow. 但是花点时间看看生成的SQL,它可能(也可能会)丑陋而缓慢。

If you are using EclipseLink you can use the FUNC() function in JPQL to call a specific database function: 如果您使用的是EclipseLink,则可以使用JPQL中的FUNC()函数来调用特定的数据库函数:

Support for Native Database Functions Using FUNC 使用FUNC支持本机数据库功能

I'm afraid that's beyond the scope of what JPQL offers. 我担心这超出了JPQL提供的范围。 You will have to resort to native queries. 您将不得不求助于本机查询。

Here's the List of available functions in JPQL: 这是JPQL中可用函数的列表:

Java EE Tutorial 6 > Persistence > JPQL > Functional Expressions Java EE教程6>持久性> JPQL>功能表达式

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

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