How to build a dynamic query which add number of days to date and compare that date with another date using criteria API?

时光总嘲笑我的痴心妄想 提交于 2019-12-05 17:42:14

You can use CriteriaBuilder#function() to execute a database function to add days into retentionDate. I've made an example with DATEADD(), as my test project runs with H2 database.

    ParameterExpression<String> dayUnit = builder.parameter(String.class, "dayUnit");
    Expression<DateTime> newDate = builder.function("DATEADD", DateTime.class, dayUnit, days, retentionDate);

And the full example:

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<B> cq = builder.createQuery(B.class);
    Root<B> fromB = cq.from(B.class);

    Expression<DateTime> lastmodifiedDate = fromB.get(B_.lastmodifiedDate);
    Expression<DateTime> retentionDate = fromB.get(B_.a).get("retentionDate");
    Expression<Integer> days = fromB.get(B_.a).get("days");

    ParameterExpression<String> dayUnit = builder.parameter(String.class, "dayUnit");
    Expression<DateTime> newDate = builder.function("DATEADD", DateTime.class, dayUnit, days, retentionDate);

    cq.where(builder.greaterThanOrEqualTo(newDate, lastmodifiedDate));

    TypedQuery<B> tq = entityManager.createQuery(cq.select(fromB));
    tq.setParameter("dayUnit", "DAY");
    List<B> results = tq.getResultList();

This query transforms into SQL as:

select 
    b0_.id as id1_1_, 
    b0_.a_id as a_id3_1_, 
    b0_.lastmodified_date as lastmodi2_1_ 
from b b0_ 
    cross join a a1_ 
where b0_.a_id=a1_.id 
    and DATEADD(?, a1_.days, a1_.retention_date)>=b0_.lastmodified_date
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!