Hibernate中乱码的解决例子之(多谢群中52313951提供)

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背后如何识别和处理“?”的呢?。。。。 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值