How to correctly convert JPQL query using “%”

2019-06-10 02:45发布

问题:

I have this query (works fine):

@Override
public List<Product> getProductsByName(String name) {
    Query q = em.createQuery("SELECT p FROM Product p WHERE p.productName LIKE '%"+name+"%'");
    @SuppressWarnings("unchecked")
    List<Product> pro = q.getResultList();
    return pro;
}

but I want to convert it into this (with .setParameter()):

@Override
public List<Product> getProductsByName(String name) {
    Query q = em.createQuery("SELECT p FROM Product p WHERE p.productName LIKE %:name %")
    .setParameter("name", name);
    @SuppressWarnings("unchecked")
    List<Product> pro = q.getResultList();
    return pro;
}

In this case i get: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: %

How corectly use % (I tried '%:name%', '%':name'%') ?

回答1:

Let's try this way :

@Override
public List<Product> getProductsByName(String name) {
  Query q = em.createQuery("SELECT p FROM Product p WHERE p.productName LIKE :name")
  q.setParameter("name", '%'+name+'%');
  @SuppressWarnings("unchecked")
  List<Product> pro = q.getResultList();
  return pro;
}