Search code examples
mysqlspringspring-bootspring-data-jpaspring-data

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


I'm trying to make simple search bar using spring and MySQL query. I used the below code to get list of customers but I'm getting error

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

Code I used:

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;
  }

}

Solution

  • Yeah, Hibernate won't let you do that. If you want your like query to work, use:

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

    Or you can even use a native query.