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

前端 未结 4 1828
无人共我
无人共我 2021-01-12 16:11

For mysql I wrote a query like

SELECT * FROM mytable GROUP BY DATE(dateTimeField)

But i can\'t use the DATE() function in JPQL

相关标签:
4条回答
  • 2021-01-12 16:54

    I'm afraid that's beyond the scope of what JPQL offers. You will have to resort to native queries.

    Here's the List of available functions in JPQL:

    Java EE Tutorial 6 > Persistence > JPQL > Functional Expressions

    0 讨论(0)
  • 2021-01-12 17:01

    If You use Hibernate under the hood you can try :

    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

      <property name="hibernate.dialect" value="my.own.CustomPostgresqlDialect"/>
      
    3. Use your function in JPQL.

      select p from Post p group by truncate_date(p.dateCreated)
      
    0 讨论(0)
  • 2021-01-12 17:02

    For Hibernate:

    Suggestion 1:

    Use cast(dateTimeField as date). See here.

    Suggestion 2:

    You can try to concatenate year, month and year HQL expressions.

    Take a look at line 360 of this testcase.

    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.

    0 讨论(0)
  • 2021-01-12 17:06

    If you are using EclipseLink you can use the FUNC() function in JPQL to call a specific database function:

    Support for Native Database Functions Using FUNC

    0 讨论(0)
提交回复
热议问题