SQLGrammarException: could not execute query

前端 未结 2 1265
醉话见心
醉话见心 2021-01-05 14:56

I am using Struts2 & Hibernate and getting below error when I searched data with string test but works for me when I searched with numeric 111.

相关标签:
2条回答
  • 2021-01-05 15:22

    The SQLGrammarException is thrown because the SQL query generated by Hibernate has wrong SQL syntax. The way you built the query is wrong, you shouldn't concatenate values (especially string values) to the result query, because such code is vulnerable for possible SQL injection attack. Instead, you can use parameters in the query string

    String empId = p.getEmpId();
    String paramValue = "";
    if (empId !=null && !empId.isEmpty())
        paramValue = " where b.empId=:empId";
    String empName = p.getEmployeeName();
    if (empName !=null && !empName.isEmpty()) {
        if (paramValue == "")
         paramValue =" where b.employeeName=:empName";
        else
         paramValue =paramValue + " and b.employeeName=:empName"; 
    }       
    System.out.println("=========paramvalues===="+paramValue);
    Query query = session.createQuery("from RequestBean b"+paramValue);
    //now set parameter values
    if(empId !=null && !empId.isEmpty())
      query.setParameter("empId", empId);
    if(empName !=null && !empName.isEmpty())
      query.setParameter("empName", empName);
    recList = (List<RequestBean>) query.list();
    
    0 讨论(0)
  • 2021-01-05 15:34

    Your hql to sql converted query is generating:

        "where employeeName=Name" 
    

    while it should be generating:

        "where employeeName='Name'".
    

    So your hql should be :

        "where b.employeeName= ' " +empName+ " ' "; 
    

    Note : You don't need to do that for integer values, only applies to String variables.

    0 讨论(0)
提交回复
热议问题