SQLGrammarException: could not execute query

佐手、 提交于 2019-12-01 06:06:57

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();

Your hql to sql converted query is generating:

    "where employeeName=Name" 

while it should be generating:

    "where employeeName='Name'".

So your hql shoul be :

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!