JPA +标准+日期处理

时间:2013-09-13 19:20:27

标签: jpa criteria-api

select * from xyz where  to_char(sdateAndTime,'DD-MM-YYYY')=(select max( to_char(sdateAndTime,'DD-MM-YYYY')) as dt from xyz))

sdateAndTime is timestamp field in oracle db. i am interested to fetch record for that given date and not in hh:mm:ss:zzzz AM/PM.

Trying to build criteria for it but :(

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<XYZ> criteria = builder.createQuery(XYZ.class);
Root<XYZ> root = criteria.from(XYZ.class);
criteria.select(root);
Subquery<XYZ> sub = criteria.subquery(XYZ.class);
Root subRoot = sub.from(XYZ.class);
sub.select(builder.max(subRoot.get("sdateAndTime")));
criteria.select(root).where(builder.in(root.get("sdateAndTime")).value(sub);
entityManager.createQuery(criteria);

我能够达到dd的提取最大值:hh:mm:ss然而无法等同于to_char(sdateAndTime,'DD-MM-YYYY')

输入将不胜感激。感谢

2 个答案:

答案 0 :(得分:2)

您可以使用function()API来调用数据库函数,例如“TO_CHAR”。

https://en.wikibooks.org/wiki/Java_Persistence/Criteria#Special_Operations

答案 1 :(得分:1)

感谢詹姆斯的投入...... !!

我使用以下更改修改了上述条件查询以获得所需结果。

Subquery<String> sub = criteria.subquery(String.class);
        Root subRoot = sub.from(XYZ.class);
        sub.select(builder.substring(builder.greatest(builder.function("TO_CHAR", String.class, subRoot.get("sdateAndTime"))),0,10));
        criteria.select(root).where(
                builder.equal(builder.substring(builder.function("TO_CHAR", String.class, root.get("sdateAndTime")),0,10),sub)

注意:我无法将DD-MM-YYYY作为参数传递,因此解决方法使用了substring。 更好的解决方案将不胜感激。