Phil_Charly
Phil_Charly

Reputation: 237

Retrieving date via Criteria fails

I want to retrieve through Hibernate via Criteria the instances which in their date column have the current date.

1) So in MySQL DB via MySQL_Workbench I inserted an instance writing in the current date '2015-07-25'.

2) My java code looks like this :

Date date = new Date();

 factory = new AnnotationConfiguration().configure().buildSessionFactory();
     Session session = factory.openSession();
     session.beginTransaction();

    Criteria cr = session.createCriteria(Logger.class);
     //the following date-like cr. fails
     cr.add(Restrictions.eq("RunDate",date));
     //this cr. runs fine alone retreiving the requested instances
     cr.add(Restrictions.like("Name", "John"));
     //The following work fine
     cr.setProjection(Projections.sum("Contacts"));
     long resultCount = (long)cr.uniqueResult();
     System.out.println(resultCount);
     ...

When running with the date criteria I have a null pointer exception.I tried also cr.like,cr.ge ... same results.

Upvotes: 0

Views: 32

Answers (1)

googol
googol

Reputation: 46

What do you have as a value in your database? if your date in your DB has time value as well and you only want to compare with the current day, you should do basically the following:

WHERE RunDate >= '2015-07-25 00:00:00' AND RunDate <= '2015-07-25 23:59:59'

like that only in an equivalent to the Criteria API

regards

Upvotes: 2

Related Questions