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
.
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 should be :
"where b.employeeName= ' " +empName+ " ' ";
Note : You don't need to do that for integer values, only applies to String variables.