开发者

HQL query using a date column

I am trying to create a query that will return a List of Person objects based on if the createDate field falls after a passed string that represents a date.

My createDate fields is mapped like this in my Person class

@Basic(optional = false)
@Column(name = "CREATE_DATE")
@Temporal(Te开发者_开发问答mporalType.DATE)
private Date createDate;

My function to find all person results after a date looks like this.

public List<Person> searchDate(String startDate) {

     Session session = getSessionFactory().openSession();

     String s_query = "FROM Person as p WHERE p.createDate >= :date";
     Query query;
     DateFormat df = new SimpleDateFormat('dd-MMM-yy');

     try {
        Date dt = df.parse(startDate);
        query = session.createQuery(s_query).setDate("date", dt);

     } catch(ParseException e){} 

     return (List<Person>)query.list();

}


I don't see any problem there. The code should work. You can try this as an alternative.

public List<Person> searchDate(String startDate) {
    Calendar cal = Calendar.getInstance();
    cal.set( year, month-1, day );
    Date createDate = cal.getTime();
    Session session = getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(Person.class ); 
    criteria.add( Restrictions.eq( "createDate", createDate) ); 
    return criteria.list();;
}

I hope this will help. If is there anything wrong discuss here because discussing is a way to learn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜