JPQL动态查询(模糊查询)中 通配符 与 动态变量 联合使用 的限制:
JPQL动态查询 参数不存在问题解决:
错误使用方式=>形如如下代码:
1/2:
public Item fuzzySearch(String name) {
String queryString = "SELECT i FROM Item i WHERE i.name LIKE '%:param%'";
Query query = em.createQuery(queryString);
query.setParameter("param", name);
return (Item) query.getSingleResult();
}
2/2:
@SuppressWarnings("unchecked")
public List<Item> fuzzySearch(String name) {
return em.createQuery("SELECT i FROM Item i " +
"WHERE i.name LIKE '%?%' ")
.setParameter(1, name)
.getResultList();
}
总会报出如下错误:
java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
java.lang.IllegalArgumentException: Parameter with that name [param] did not exist
亦或是
(javax.servlet.ServletException: javax.servlet.ServletException: Parameter with that position [1] did not exist)
(javax.servlet.ServletException: javax.servlet.ServletException: Parameter with that name [param] did not exist)
解决方法:
核心思想:将 通配符 挪到变量里就可以了~
正确用法:
public Item singleFuzzySearch(String name) {
String queryString = "SELECT i FROM Item i WHERE i.name LIKE :param";
Query query = em.createQuery(queryString);
query.setParameter("param", "'%"+name+"%'");
return (Item) query.getSingleResult();
}
@SuppressWarnings("unchecked")
public List<Item> fuzzySearch(String name) {
return em.createQuery("SELECT i FROM Item i " +
"WHERE i.name LIKE ? ")
.setParameter(1, "'%" + name + "%'" )
.getResultList();
}
使用时需注意:
1. 通配符(%)的位置,位置变量(?)的参数
2. :param / ? 、得到对象单值/List