【问题标题】:Hibernate criteria group by date without time休眠条件按日期分组,没有时间
【发布时间】:2013-05-04 11:28:41
【问题描述】:

这段代码给了我两个项目日期时间和计数的列表。但我需要按日期分组,没有时间。

谁能告诉我怎么做?谢谢!

    Criteria criteria = getSession().createCriteria(Parcel.class);

    ProjectionList projectionList = Projections.projectionList(); 

        projectionList.add(Projections.groupProperty("dateCreated"));
        projectionList.add(Projections.rowCount());

    criteria.setProjection(projectionList);


    List<Object[]> results = criteria.list();

结果:

2013-04-27 11:08:00.0 | 32

2013-04-27 11:10:00.0 | 5

2013-04-28 15:03:27.0 | 12

我需要:

2013-04-27 | 37

2013-04-28 | 12

【问题讨论】:

    标签: java hibernate criteria date-formatting


    【解决方案1】:

    您可能会发现Projections#sqlGroupProjection 方法很有用。它允许您使用 SQL 函数 date() 提取 Date 形成 DateTime 列。基本上,而不是调用

    projectionList.add(Projections.groupProperty("dateCreated"));
    

    使用

    projectionList.add(Projections.sqlGroupProjection("date(dateCreated) as createdDate", "createdDate", new String[] { "createdDate" }, new Type[] { StandardBasicTypes.DATE }));
    

    【讨论】:

    • 效果很好,但我必须将实体字段的名称(在您的示例中为dateCreated)替换为列名(在您的示例中为date_created)。如果我不这样做,它会抱怨 *in 小写 *(?) 列(在您的示例中为 datecreated)不存在。
    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 2011-08-13
    • 2015-09-08
    • 2018-06-20
    • 2014-12-12
    • 2012-12-21
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多