String str = "中文字符串";
String hql = "FROM Table AS t WHERE t.field like '%" + str + "%'";
Query query = getSession().createQuery(hql);
query.list();
使用这种形式传入参数str, 会导致控制台输出:
FROM Table AS t WHERE t.field like '% ????%'
之类的乱码, 从而在数据库找不到匹配记录.
据说这是hibernate3.0 like子句处理中文的一个问题, 3.1已得到修正。3.0版可以通过设置参数解决。改正如下:
String str = "中文字符串";
String hql = "FROM Table AS t WHERE t.field LIKE :param";
Query query = getSession().createQuery(hql);
query.setString("param", "%" + str + "%");
query.list();