有一个查询
String str="From Table where col1=? and col2=? and col3=col4";使用getHibernateTemplate().find(str,new Object[]{"aaa","bbb","ccc"});
始终查询不出结果。但打印出来的sql语句却可以查询。将字符串改为
String str="From Table where col1='"+aaa+"' and col2='"+bbb+"' and col3=col4";
getHibernateTemplate().find(str);却可以正常读出。这是为什么呢?

解决方案 »

  1.   

    String str="From Table where col1=? and col2=? and col3=col4";
    使用getHibernateTemplate().find(str,new Object[]{"aaa","bbb","ccc"});
    想问一下,你本来只有两个问号,但是你传3个参数?
    那个CCC的值应该给哪个?
      

  2.   


    为什么一定要左右做呢? 
    如果要传送参数,直接写个方法
    String sql = "";
    然后etHibernateTemplate().find(sql+参数1,参数2)
      

  3.   

    对不起,是两个参数。我没copy代码。只是手写出来的。笔误。对不起。我记得find(String,Object[]obj)这种查询方法应该是可行的呀,以前做也是这么做。但不晓得为什么就是查不出来。
      

  4.   


    楼主可以按下面这样修改试试:
    String str="From Table where col1='?' and col2='?' and col3='?'";使用getHibernateTemplate().find(str,new Object[]{"aaa","bbb","ccc"});可能原因是你查询的字段是字符串字段,所以在HQL中要加单引号,如果是hibernate的
    query.setString(0,str);
    这种方式的话,他是会自己加上单引号的你println的sql语句可以查询与这个没什么关系,因为在控制台中输入sql语句,控制台比较灵活,可以自己识别一下,比如 int型的id, 也可以 where id='1001'。
      

  5.   

    String str="From Table where col1=? and col2=? and col3=col4";使用getHibernateTemplate().find(str,new Object[]{"aaa","bbb","ccc"});
    始终查询不出结果。但打印出来的sql语句却可以查询。肯定查不出来呀,你给了参数值,Hibernate怎么知道aaa对应的是哪个?
    不过我个人喜欢下面的做法:
    String str="From Table where col1=:col1 and col2=:col2 and col3=col3";
    String[] params = {"col1","col2","col3"};
    Object[] value = {"aaa","bbb","ccc"};
    return super.getHibernateTemplate().findByNamedParam(str, param, value);
      

  6.   

    上面发的String str="From Table where col1=:col1 and col2=:col2 and col3=col3";这里有一点错误,既col3=col3这里,要加一个:
    String str="From Table where col1=:col1 and col2=:col2 and col3=:col3";
      

  7.   

    正解,hibernate无法匹配啊。如果只有一个参数可以这样,但是如果有多个参数
    getHibernateTemplate().find(str,new String[]{"col1","col2"},new Object[]{"aaa","bbb"}),这样铁定没问题
      

  8.   

    String str="From Table where col1=? and col2=? and col3=col4";这个也应该用参数命名法吧。
    String str="From Table where col1=:col1 and col2=:col2 and col3=col4";