JPA學習(五):java持久化查詢語言JPQL--動態查詢的使用及語法限制
阿新 • • 發佈:2019-02-04
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