如何解决此错误 org.hibernate.hql.internal.ast.QuerySyntaxException:意外标记:%

How to solve this error org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: %

我正在尝试使用 spring 和 MySQL 查询制作简单的搜索栏。我使用以下代码获取客户列表,但出现错误

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: %.

我使用的代码:

public List<CustDTO> getCust(String name) throws Exception {
  List<CustDTO> customerList=null;

  String queryString ="SELECT c FROM Cust c WHERE c.name LIKE %?1%";
  Query query=entityManager.createQuery(queryString);
  query.setParameter(1, name);
    
  List<Cust> result = query.getResultList();

  customerList=new ArrayList<CustDTO>();

    for (Cust customerEntity : result) {
        CustDTO customer=new CustDTO();
        customer.setName(customerEntity.getName());
        customer.setCity(customerEntity.getCity());

        customerList.add(customer);
    }
    System.out.println(customerList);
    return customerList;
  }

}
public List<CustDTO> getCust(String theSearchName) throws Exception {

Query theQuery = null;

theQuery = createQuery("from CustDTO where lower(name) like :theName", CustDTO.class);
query.setParameter("theName", "%" + theSearchName.toLowerCase() + "%");

    List<CustDTO> customers = theQuery.getResultList();
                
    return customers;

lower(name) - name 是来自您的 CustDTO 实体的字段。

您还可以添加检查您的输入是否为空

if (theSearchName != null && theSearchName.trim().length() > 0) {

        // do search with like
    }else {
        // theSearchName is empty ... so just get all customers
        theQuery =currentSession.createQuery("from CustDTO", CustDTO.class);            
    }

是的,Hibernate 不允许您这样做。 如果你想让你的 like 查询起作用,请使用:

   String queryString ="SELECT c FROM Cust c WHERE c.name LIKE ?1";
    Query query=entityManager.createQuery(queryString);
    query.setParameter(1, "%"+name+"%”);

或者您甚至可以使用本机查询。