是否可以创建动态JPQL查询?

时间:2015-07-03 15:17:47

标签: java jpa 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,我理解为什么会这样,但我怎么能避免这个问题?

1 个答案:

答案 0 :(得分:9)

你可以试试。

    public List<Prod> get(String category, String name, Integer priceMin, Integer priceMax){
    Map<String, Object> paramaterMap = new HashMap<String, Object>();
    List<String> whereCause = new ArrayList<String>();

    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("select p from Prod p ");

    if (!category.isEmpty()){
        whereCause.add(" p.cat.name =:category ");
        paramaterMap.put("category", category);
    }
    if (!name.isEmpty()){
        whereCause.add(" p.name =:name ");
        paramaterMap.put("name", name);
    }
    if (priceMin!=null){
        whereCause.add(" p.price>=:priceMin ");
        paramaterMap.put("priceMin", priceMin);
    }
    if (priceMax!=null){
        whereCause.add("p.price<=:priceMax  ");
        paramaterMap.put("priceMax", priceMax);
    }

    //.................
    queryBuilder.append(" where " + StringUtils.join(whereCause, " and "));
    Query jpaQuery = entityManager.createQuery(queryBuilder.toString());

    for(String key :paramaterMap.keySet()) {
            jpaQuery.setParameter(key, paramaterMap.get(key));
    }

    return  jpaQuery.getResultList();

}