HQL query using a date column

♀尐吖头ヾ 提交于 2019-12-11 23:38:59

问题


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(TemporalType.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();

}

回答1:


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.



来源:https://stackoverflow.com/questions/5423296/hql-query-using-a-date-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!