Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 to datetime column and I only want to pull rows where todays date falls in between the from and to.

I am using JPA 2.0 running off of Hibernate.

    Date currentDate = new Date();
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Experience> query = builder.createQuery(Experience.class);
    Root<Experience> root = query.from(Experience.class);
    builder.between(currentDate, root.get("from"), root.get("to"));
    return entityManager.createQuery(query).getResultList();

My issue is that builder.between() obviously wont allow me to pass a Date object.

Is there a better solution to my problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
329 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...