我正在尝试使用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;
}
}
是的,Hibernate不允许你这样做。如果你想让你的like查询工作,使用:
String queryString ="SELECT c FROM Cust c WHERE c.name LIKE ?1";
Query query=entityManager.createQuery(queryString);
query.setParameter(1, "%"+name+"%”);
或者你甚至可以使用本地查询。
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;
低(名称) - 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);
}