2

从hibernate3升级到hibernate4后,旧项目代码抛出警告信息:

org.hibernate.hql.internal.ast.HqlSqlWalker [HqlSqlWalker.java:929] [DEPRECATION] Encountered positional parameter near line 1, column 56.  Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.

答案可以从以下链接中找到:

  1. 如何修复带有弃用警告的 Hibernate 查询?
  2. https://hibernate.atlassian.net/browse/HHH-7023

但我想知道修改以下代码以避免此警告的最佳方法是什么?

StringBuffer hql = new StringBuffer("from Record where 1=1");
List<Object> params = new ArrayList<Object>();
if (subject!= null && subject.trim().length() > 0) {
    hql.append(" and subjectlike ?");
    params.add("%" + subject.trim() + "%");
}
if (startDate != null) {
    hql.append(" and createTime> ?");
    params.add(startDate);
}
if (endDate != null) {
    hql.append(" and createTime< ?");
    params.add(endDate);
}
Query query = getSession().createQuery(hql);
if (params.length > 0) {
   for (int i = 0, length = params.length; i < length; i++)
        query.setParameter(i, params.get(i));
}
List result = query.list();


==>update20130401,通过在每个参数标记“?”后添加订单号来将 HQL 更改为 JPQL 样式:

//first, fomat HQL to JPQL style
private String fomatHQL(CharSequence queryString) {     
            StringBuffer buffer = new StringBuffer(queryString);
            int start = 0;
            int order = 0;
            while ((start = buffer.indexOf("?", start + 1)) > 0) {
                buffer.insert(start + 1, order);
                order++;
            }
            return buffer.toString();

    }
// second, create Query
// third, set parameters
protected void setParameterList(Query query, Object[] params) {
        if (params != null && params.length > 0) {
            for (int i = 0, length = params.length; i < length; i++)
                query.setParameter(i + "", params[i]);
        }
    }
4

1 回答 1

4
    StringBuilder hql = new StringBuilder("from Record where 1=1");
    Query query = getSession().createQuery(hql);
    if (subject!= null && subject.trim().length() > 0) {
        hql.append(" and subjectlike :subject");
        query.setParameter("subject", "%" + subject.trim() + "%");
    }
    if (startDate != null) {
        hql.append(" and createTime> :startDate");
        query.setParameter("startDate", startDate);
    }
    if (endDate != null) {
        hql.append(" and createTime< :endDate");
        query.setParameter("endDate",endDate);
    }
    List result = query.list();

首选StringBuilderStringBuffer因为最后一个是同步的,因此性能较低,除非您处于并发上下文中(此处不是这种情况)

于 2013-03-28T15:22:39.053 回答