用hibernate做mysql的数据库连接时,当查询条件中有中文的时候,查询结果没有记录,而数据库中是存在符合条件的记录的。
如下面的查询语句:
select t.id.student.sid from Studentcourse as t where t.fkTid='"+tid+"' and t.id.fkCid='"+cid+"' and t.fkClassId='"+classId+"' and t.fkSemester='"+semester+"' order by t.id.student.sid desc
其中where条件中的classId和semester是中文的。
用这条语句查询到的记录为空。
这一问题原来是没有的,重新部署后才出现,所以由于字符集的问题造成的,但我改了很多次字符集都搞不定,数据库、jsp、及数据库连接改成一致的时候也解决不了问题。
后来有一个比较麻烦的办法,但是可以解决问题,就是改写查询语句的书写方式:将变量值的指定写在语句外面
原来的方式:
List sc=session.createQuery("select t.id.student.sid from Studentcourse as t where t.fkTid='"+tid+"' and t.id.fkCid='"+cid+"' and t.fkClassId='"+classId+"' and t.fkSemester='"+semester+"' order by t.id.student.sid desc").list();
现在的方式:
String sqlString = "select t.id.student.sid from Studentcourse as t where t.fkTid=:tid and t.id.fkCid=:cidand t.fkClassId=:classId and t.fkSemester=:semester order by t.id.student.sid desc";
Query query = session.createQuery(sqlString);
query.setString("tid", tid);
query.setString("cid", cid);
query.setString("classId", classId);
query.setString("semester", semester);