1
我需要創建一個動態查詢。我試圖用JPQL來做,但不能。 例如:是否可以創建一個動態的JPQL查詢?
public List get(String category, String name, Integer priceMin, Integer priceMax){
List<Prod> list;
String query = "select p from Prod p where 1<2 ";
String queryCat="";
String queryName="";
String queryPriceMin="";
String queryPriceMax="";
String and = " and ";
if (!category.isEmpty()){
query+=and+"p.cat.name=:category ";
}
if (!name.isEmpty()){
query+=and+"p.name=:name ";
}
if (priceMin!=null){
query+=and+"p.price>=:priceMin ";
}
if (priceMax!=null){
query+=and+"p.price<=:priceMax ";
}
return list = entityManager.createQuery(query)
.setParameter("category", category)
.setParameter("name",name)
.setParameter("priceMin", priceMin)
.setParameter("priceMax", priceMax)
.getResultList();
}
如果有所有的參數,查詢運行,但如果沒有這樣的參數category
我有例外java.lang.IllegalArgumentException: Parameter with that name [category] did not exist
,我明白爲什麼會這樣,但我怎麼能避免這個問題?
是的,它在IDEA中工作,但是當我用MAVEN打包項目時,我得到這個錯誤:package com.sun.deploy.util does not exist。我需要添加依賴項? –
請檢查:http://stackoverflow.com/a/10667275/1638718 – ozgur