Search code examples
jpaprepared-statement

how to parametrize a single query


i would like to have a query that contains all the category selected something like : in ProductDao

enter public List<Product> listselected(List <Product> selectedCategories) { 
     TypedQuery<Product> findQuery = em
            .createQuery(
                    "SELECT DISTINCT p FROM Product p WHERE p.idcategory='1' AND p.idcategory='2' etc ORDER BY p.idproduct",
                    Product.class);
    return findQuery.getResultList();} here

but parametrized


Solution

  • You can use this syntax:

    em.createQuery("SELECT DISTINCT p FROM Product p WHERE p.idcategory IN (:categories) ORDER BY p.idproduct", Product.class)
             .setParameter("categories", selectedCategories)
             .getResultList();
    

    Now, I don't know how you mapped a Category, but if it's an entity and Product has a field category, you can rewrite the query with:

    List<Category> selectedCategories =...;
    em.createQuery("SELECT DISTINCT p FROM Product p WHERE p.category IN (:categories) ORDER BY p.idproduct", Product.class)
             .setParameter("categories", selectedCategories)
             .getResultList();
    

    I don't know if this is standard JPA, but it should work with Hibernate ORM.