日期:2014-05-19  浏览次数:20743 次

路过的大虾,帮忙看下hibernate查询
Java code

/*
* Find all events in the given month and year.
* @param month - 0-11 (0 = January)
* @param year
*/
  public List findEventsFor(int month, int year) {
  List events = null;
      try {
      startOperation();
      Date firstDay = DateUtils.newDate(month, 1, year);
      Date lastDay = DateUtils.newDate(month + 1, 1, year);
          StringBuffer sql = new StringBuffer();
      sql.append("from Event event where 1=1 and event.startDate >= :firstDay and event.startDate < :lastDay");
      Query query = getSession().createQuery(sql.toString());

      query.setParameter("firstDay", firstDay);
      query.setParameter("lastDay", lastDay);
      events =  query.list();
      getTx().commit();
  } catch (HibernateException e) {
      handleException(e);
  } finally {
      HibernateFactory.close(getSession());
  }
  return events;
}


如果在创建Query对象之后,在追加sql会有问题?
parameter username does not exist as a named parameter in
原因也很简单,对象创建完成之后再追加的sqlhibernate是不知道的,此种问题有遇到过的吗?麻烦给出解决方案,谢!
Java code

StringBuffer sql = new StringBuffer();
sql.append("from Event event where 1=1 ");
Query query = getSession().createQuery(q);
if(null != startData && null != lastDay) {
   sql.append("and event.startDate >= :firstDay and event.startDate < :lastDay");
}
query.setParameter("firstDay", firstDay);
query.setParameter("lastDay", lastDay);




------解决方案--------------------
你必须要用query吗,不是必须的话,可以用别的方法如:
StringBuffer sql = new StringBuffer();
sql.append("from Event event where 1=1 and event.startDate >= ? and event.startDate < ?);

List list = this.getHibernateTemplate().find(queryString, new Object[]{firstDay,lastDay});
不知道行不,可以试一下
------解决方案--------------------
探讨

你必须要用query吗,不是必须的话,可以用别的方法如:
StringBuffer sql = new StringBuffer();
sql.append("from Event event where 1=1 and event.startDate >= ? and event.startDate < ?);

List list = this.getHibernateT……

------解决方案--------------------
缓存查询条件,重新准备SQL语句不行吗?