Search code examples
javahibernatedatecriteria

Hibernate criteria get all rows where currentDate > startDate and < endDate


I need get all rows where current date contains beetwen dateStart and dateAnd.

if current date - 17 JAN 2017 and

id  dateStart     dateEnd
0   01 JAN 2017   18 JAN 2017
1   01 JAN 2017   16 JAN 2017
2   18 JAN 2017   03 FEB 2017
4   17 JAN 2017   16 JAN 2017

I need get 2 rows with 0 and 4 ID in table

@Override
    public List<Raffle> findCurrentRaffle() {
        Criteria criteria = getSession().createCriteria(Raffle.class);
        criteria.add(Restrictions.ge("dateStart",  new Date()));
        criteria.add(Restrictions.le("dateEnd", new Date()));
        return criteria.list();
    }

return 0 rows

private Long id;
    @Column(name = "dateStart")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateStart;
    @Column(name = "dateEnd")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateEnd;

Solution

  • In you conditions you have dateStart >= currentDate and dateEnd <= currentDate

    To solve a problem, just change condition to dateStart <= currentDate and dateEnd >= currentDate

    criteria.add(Restrictions.le("dateStart",  new Date()));
    criteria.add(Restrictions.ge("dateEnd", new Date()));