命名参数未绑定

Named parameters not bound

我有多个 HQL 语句容易受到 SQL 注入示例的影响:

public List<Person> SearchList(String userName, String firstName, String lastName, String email) Exception {
   List<Person> personList = new ArrayList<>();
   String hql = " FROM **.***.***.entity.Person P WHERE ";
   boolean buName = false;
   boolean bfName = false;
   if (StringUtils.isNotEmpty(userName)){
      hql = hql + "lower(P.userName) like :userName "; 
      buName = true;
   }
   if (StringUtils.isNotEmpty(firstName) && StringUtils.isNotEmpty(lastName)){    
      if(buName){
         hql = hql + " OR ";
      }
      hql = hql + "(lower(P.firstName) like :firstName AND lower(P.lastName) like :lastName) ";  
      bfName = true;    
   }
   if (StringUtils.isNotEmpty(internetAddr)){    
      if(buName || bfName){
         hql = hql + " OR ";
      }
      hql = hql + "lower(P.email) = :email"; 
   }
   try {
      Query query = getCurrentSession().createQuery(hql);
        
      if (StringUtils.isNotEmpty(userName)) {
         query.setParameter("userName", '%'+userName.toLowerCase()+'%');
      } else if (StringUtils.isNotEmpty(firstName) && StringUtils.isNotEmpty(lastName)) {
         query.setParameter("firstName", '%'+firstName.toLowerCase()+'%');
         query.setParameter("lastName", '%'+lastName.toLowerCase()+'%');
      } else if (StringUtils.isNotEmpty(email)) {
         query.setParameter("email", email.toLowerCase());
      }

      personList = query.list();
   } catch(Exception e){
      throw new Exception(e.getMessage());
   }
   return personList;
}

我在这里避免查询 "'%" + userName + "%'" 中的连接以避免 SQL 注入漏洞,现在我看到与

相关的异常
Named parameters not bound: lastname

这是基于 firstname 的搜索而发生的。我怎样才能避免这种情况?

你应该更正这个:

if (StringUtils.isNotEmpty(userName)) {
   query.setParameter("userName", '%'+userName.toLowerCase()+'%');
} else if (StringUtils.isNotEmpty(firstName) && StringUtils.isNotEmpty(lastName)) {
   query.setParameter("firstName", '%'+firstName.toLowerCase()+'%');
   query.setParameter("lastName", '%'+lastName.toLowerCase()+'%');
} else if (StringUtils.isNotEmpty(email)) {
   query.setParameter("email", email.toLowerCase());
}   

对此:

if (StringUtils.isNotEmpty(userName)) {
   query.setParameter("userName", '%'+userName.toLowerCase()+'%');
}
if (StringUtils.isNotEmpty(firstName) && StringUtils.isNotEmpty(lastName)) {
   query.setParameter("firstName", '%'+firstName.toLowerCase()+'%');
   query.setParameter("lastName", '%'+lastName.toLowerCase()+'%');
}
if (StringUtils.isNotEmpty(email)) {
   query.setParameter("email", email.toLowerCase());
}   

因为您应该将命名参数添加到 HQL 并通过 query.setParameter 一致地设置它们。

注意

I am avoiding concatenations in the query "'%" + userName + "%'" to avoid SQL injection vulnerability

您可以在 HQL 中使用 concatenation (operation),如下所示:

... 
lower(P.userName) like '%' || :userName || '%'
...

它也可以让您避免 SQL 注入。但请注意,这 like 很可能会导致 full table scan.