Hibernate中文查询(SSH开发, Hibernate 3.2)
用户从JSP页面的Form里面输入关键字,比如 "海 ",然后提交,Struts的Action中进行处理,调用service逻辑:
public class AdminServiceImp implements IAdminService {
....
private final String LOAD_HQL_NAME_CORP_RECORDS = "from TCorp rc where rc.name like ? order by rc.id ";
....
public Collection getNamePatternCorpRecords(String pageMethod, String namePattern)
{
String loadHQL;
String loadTempHQL;
String tempKey;
tempKey = " '% " + namePattern + "% ' ";
loadTempHQL = this.LOAD_HQL_NAME_CORP_RECORDS;
loadHQL = loadTempHQL.replaceAll( "[?] ", tempKey);
return this.getCorpRecords(pageMethod, countHQL, loadHQL);
}
....
}
方法getNamePatternCorpRecords被Action的execute调用,参数namePattern就是从JSP页-> Action传进来的查询关键字,Action中不对关键字做任何处理,在这个方法中将关键字用%拼起来再拼成HQL串穿给DAO的方法getCorpRecords,getCorpRecords就是具体执行HQL操作的类,没什么特别的,没有任何问题.
如果用户输入的是英文串,以上都没有任何问题,但是一旦是中文,会发现getNamePatternCorpRecords中拼完后形成的中文字符是乱码,以下是Hibernate打出来的HQL:
Hibernate: select tcorp0_.ID as ID1_, tcorp0_.name as name1_, tcorp0_.address as address1_, tcorp0_.phone as phone1_, tcorp0_.fax as fax1_, tcorp0_.intro as intro1_, tcorp0_.homepage_url as homepage7_1_ from corp tcorp_ where tcorp0_.name like '%??·% ' order by tcorp0_.ID limit ?
用户输入的 "海 "变成了 "??· "
请问什么原因?
数据MySQL 5, 存储指定为UTF8
JSP页面也写了 <%@ page contentType= "text/html; charset=UTF-8 " %> -这样就是UTF8了
------解决方案--------------------没必要这么麻烦,在hibernate.cfg.xml中加入
<property name= "hibernate.query.factory_class ">
org.hibernate.hql.classic.ClassicQueryTranslatorFactory
</property>
就可以了.
------解决方案--------------------mark
------解决方案--------------------编码统一了就OK了,不会有乱码的.