Using JPA/Hibernate Criteria to pull between a date

前端 未结 4 1296
清歌不尽
清歌不尽 2020-12-08 06:02

I am trying to using the following code to pull a list of Experience objects from a MySQL table. Each experience has a from datetime column and a t

相关标签:
4条回答
  • 2020-12-08 06:20

    This link looks promising: http://www.javalobby.org/articles/hibernatequery102/

    You can use the criteria.ge("date", root.get("from")); and criteria.le("date"), root.get("to")); to create the between claus

    If those aren't available, then you might need to look into writing HQL.

    0 讨论(0)
  • 2020-12-08 06:27

    You should switch your arguments:

    builder.between(root.<Date>get("dateColumn"), startDate, endDate);
    
    0 讨论(0)
  • 2020-12-08 06:29

    You can pass it as a parameter:

    ParameterExpression<Date> d = builder.parameter(Date.class);
    builder.between(d, root.<Date>get("from"), root.<Date>get("to")); 
    return entityManager.createQuery(query)
        .setParameter(d, currentDate, TemporalType.DATE).getResultList(); 
    

    Note that in this case you need to specify desired temporal type.

    Also you can rely on the database's current date: builder.currentDate(), builder.currentTimestamp(), etc

    0 讨论(0)
  • 2020-12-08 06:29

    You're just missing the call to CriteriaBuilder.literal():

    Date currentDate = new Date();
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Experience> query = builder.createQuery(Experience.class);
    Root<Experience> root = query.from(Experience.class);
    builder.between(builder.literal(currentDate), root.get("from"), root.get("to"));
    return entityManager.createQuery(query).getResultList();
    
    0 讨论(0)
提交回复
热议问题