Satish N
Satish N

Reputation: 95

How to match date value to a column which has timestamp values in Hibernate Criteria?

I want to match date 2014-08-26 value to a column(called update_date) which has timestamp datatype.

Criteria criteria=createEntityCriteria(Order.class);
criteria.add(Restrictions.eq("updatedDate",transactionDate1));

When I used above code it does not return any thing because of data type mismatch.

select * from order_master where security_id=2 and client_master_id=3 and update_date="2014-08-26 19:04:14";

Above query returns exact result.Main Problem is I Only have the data 2014-08-26 but not update time. Please let me know what should I do to get the correct result in Hibernate Criteria.

Upvotes: 0

Views: 5267

Answers (2)

Learner
Learner

Reputation: 21393

Refer to this post --> Hibernate Criteria for Dates

As per this post you cannot use Restrictions.eq() or Restrictions.like() for comparing dates.

Here is the code that works for you:

To compare dates between 2 ranges:

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

        String startDateStr = "18-08-2014";
        String endDateStr = "27-08-2014";

        Date startDate = formatter.parse(startDateStr);
        Date endDate = formatter.parse(endDateStr);

        List<Order> orders = session.createCriteria(Order.class)
                .add(Restrictions.between("updatedDate", startDate, endDate))
                .list();
        for (Order order : orders) {
            System.out.println(order.getUpdatedDate());
        }

If you want to get records for a single day then you can replace the field endDate with:

Date endDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));

Upvotes: 2

Ankur Singhal
Ankur Singhal

Reputation: 26067

Something like below

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

Upvotes: 2

Related Questions