3

I have table with timestamp column and want to create Hibernate criteria projection to group me results only by date from that timestamp column (the results in database are YYYY-MM-DD HH:mm:ss). I know that I have to use Projection.sqlGroupProjectionbut not quiet sure hot to do so.

Also, is it possible to write same projection for both MySQL and Oracle ?

2 Answers 2

8

You could try using the date function inside your sqlGroupProjection:

Projections.sqlGroupProjection("date(timestampField) as myDate", "myDate", new String[] { "myDate" }, new Type[] { StandardBasicTypes.DATE })
2
  • 1
    And that part is failing on Oracle but works on MySQL. On Oracle its written with trunc(timestampField) but it gives me error uknown identifier Commented Oct 17, 2014 at 11:00
  • Are you using myDate for something else? (For example to order)
    – JCalcines
    Commented Oct 31, 2014 at 10:20
4

Also, if you need to order by that column, you need to create an alias for that column

Projections.alias(Projections.sqlGroupProjection(
    "trunc(timestampField) as myDate", "myDate", 
            new String[] { "myDate" }, 
            new Type[] { StandardBasicTypes.DATE }), "myDateOrder"))

Then you can use:

criteria.addOrder(Order.asc("myDateOrder"));

Note: My answer is based on nuno answer adding the order capability.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.