Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

java - Compare date's date part only with Timestamp in Hibernate

I have timestamp in database and in application i do have date . I like to write hibernate criteria in the way that hibernate can pull all entries those matches with date, not time part. e.g.

in DB timestamp

2011-12-01 15:14:14

and in application i do have java.util.Date which has by default time part.

my problem is when i search entries from database with following code i get nothing

    DetachedCriteria criteria = DetachedCriteria.forClass(MyClass.class);
    criteria.add(Restrictions.like(TIMESTAMP_FIELD, javaUtilDate));
    List entries =this.getHibernateTemplate().findByCriteria(criteria);

thanks in advance

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you are looking for a general use of filtering by date range (eg. from today until tomorrow). I use it that way:

YourService.java

Date fromTimestamp = new Date();
Date toTimestamp = new Date();
Date fromDate = DateHelper.getDateWithoutTime(fromTimestamp);
Date toDate = DateHelper.getDateWithoutTime(DateHelper.getTomorrowDate(toTimestamp));

YourDAO.java

criteria.add(Restrictions.ge(TIMESTAMP_FIELD, fromDate));
criteria.add(Restrictions.le(TIMESTAMP_FIELD, toDate));

DateHelper.java

public static Date getDateWithoutTime(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}

public static Date getTomorrowDate(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, 1);
    return cal.getTime();
}

And of course - there is always space for refactoring in every code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...