简体   繁体   中英

How do I group by date with QueryDsl?

I have an entity and need to get a list of dates irrespective of the time. How do I group by dates?

@Entity
public class RssFeedEntry {

   //...
@Column
@Temporal(TemporalType.TIMESTAMP)
private Date publishedDate;
   //...
}

The query like this throws an exception.

JPAQuery query = new JPAQuery(entityManager);

    List<Tuple> list = query.
            from(feedEntry).
            groupBy(feedEntry.publishedDate.dayOfYear(), feedEntry.publishedDate.year()).
            list(feedEntry.publishedDate.dayOfMonth(), 
            feedEntry.publishedDate.month(),       
            feedEntry.publishedDate.year());

Stacktrace:

Caused by: org.h2.jdbc.JdbcSQLException: Column "RSSFEEDENT0_.PUBLISHEDDATE" must be in the GROUP BY list; SQL statement:

Thanks.

As far as I know, it's database restriction. All columns in the select clause must be in the group by clause unless it's used only in an aggregate function (ie max(), sum() etc.). If you are using MySQL, which is not the case, you would not have this kind of problem. MySQL is the only DB, that I am aware of, which doesn't hold you back in this matter.

Try this:

List<Tuple> list = query.
            from(feedEntry).
            groupBy(feedEntry.publishedDate.dayOfMonth(), 
            feedEntry.publishedDate.month(),       
            feedEntry.publishedDate.year()).

            list(feedEntry.publishedDate.dayOfMonth(), 
            feedEntry.publishedDate.month(),       
            feedEntry.publishedDate.year());

EDIT:

That would be more legible, though:

List<Tuple> list = query.
            from(feedEntry).
            groupBy(feedEntry.publishedDate).
            list(feedEntry.publishedDate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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