public List findByLike(String propertyName, String condition){
log.debug("finding entries by like.");
try{
List entries = null;
try {
System.out.println("1- Inside the findByLike() : " + condition);
condition = new String(condition.getBytes("ISO-8859-1"), "utf-8");
System.out.println("2- Inside the findByLike() : " + condition);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String hql = "from GrammarEntry as ge where ge." + propertyName + " like ?";
Query qry = getSession().createQuery(hql);
qry.setString(0, "%"+condition+"%");
entries = qry.list();
getSession().close(); //注意Session的关闭位置: 在Query使用之后, 因为关闭时会同时关闭其关联的所有对象.
return entries;
} catch (RuntimeException re){
log.error("find by like failed.", re);
throw re;
}
}
下面是系统输出:
1 - Inside the findByLike() : 及物动词
log4j:WARN Please initialize the log4j system properly.
2 - Inside the findByLike() : ???????
from GrammarEntry as ge where ge.grammarNote like '%???????%'
Hibernate: select grammarent0_.id as id, grammarent0_.grammarnote as grammarn2_3_, grammarent0_.sentence as sentence3_, grammarent0_.addtime as addtime3_ from gamecenter.grammarentries grammarent0_ where grammarent0_.grammarnote like '%???????%'
--- 输出结束@!
把下面的字符集"utf-8"换成GBK、GB2312都不行。
condition = new String(condition.getBytes("ISO-8859-1"), "utf-8");
解决方案1:
public List findByLike(String propertyName, String condition){
log.debug("finding entries by like.");
try{
List entries = null;
String hql = "from GrammarEntry as ge where ge." + propertyName + " like ?";
Query qry = getSession().createQuery(hql);
qry.setString(0, "%" + condition + "%");
entries = qry.list();
getSession().close();
return entries;
} catch (RuntimeException re){
log.error("find by like failed.", re);
throw re;
}
}
问题虽然解决了,还是有不明白的地方。CSDN上有人说“这是hibernate3用antlr处理含中文的hql字串导致的。不要拼hql字串,用"like ?"”。
具体Hibernate背后如何识别和处理“?”的呢?。。。。