在做项目的时候遇到一个非常奇葩的问题,一下是我的代码:
// 验证该文件名是否存在
public boolean verifyAppName(String appName, int customerId, int typesName) {
String hql = "from CustomerApplication where typeId = '" + typesName + "' and customerId = '" + customerId+ "' and customerAppName = '"+appName+"'";
Session sess = (Session) HibernateSessionFactory.getSession();
Query q = sess.createQuery(hql);
List list = q.list();
HibernateSessionFactory.closeSession();
System.out.println("CustomerApplicationBean.verifyAppName()"+typesName+"----"+appName.trim()+"---"+customerId+"----"+appName+"----"+list.size());
if (list.size() != 0) {
return true;// 返回true表示数据库中已经有了
} else {
return false;
}
}
无论如何都查询不出想要结果,开始我以为是语法有误,于是检查了大半天,可是没有发现有错,况且如果语法真有错的话,系统会报:java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V....这种错误的。
然后我就开始考虑是满足条件的数据不存在,于是我在SQL sever里面新建查询,使用一样的条件进行查询,让我大为吃惊的是,竟然查出数据了!!这下我就有点懵逼了!于是我输出接受到的参数以后,就发现端倪所在了:
为什么我输出的list.size()平白无故换行了??问题应该就出在这里了!!!于是我调用.trim()方法把参数进行去空格以后,竟然真的能够查询出结果了。
这下就真相大白了,查不出理想的结果的原因就是我接收到的参数不是我想象中的参数:接收到的参数后面还有其他看不见的字符,将之去掉以后问题就解决了。