从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.
答案可以从以下链接中找到:
但我想知道修改以下代码以避免此警告的最佳方法是什么?
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]);
}
}