JPA request by setting parameter to request object returns empty list

I am trying to query a datastore using two approaches:

Approach 1 : value of parameter Hardcode in querystring:

 String queryString="SELECT b FROM Item AS b WHERE b.categoryId=4";
 Query q = mgr.createQuery(queryString);
 List<Item> itemList = (List<Item>) q.getResultList();

      

Approach 2 : set a parameter to the request object:

 String queryString="SELECT b FROM Item AS b WHERE b.categoryId=:catId";
 Query q = mgr.createQuery(queryString);
 String parameterValue="4";
 q.setParameter("catId", parameterValue);
 List<Item> itemList = (List<Item>) q.getResultList();

      

While the first approach returns the results correctly, the second approach always returns an empty list. Why is this so? Is there a way to check if the parameter is set correctly in the request object?

+3


source to share


2 answers


If you want to get posts based on categoryId use below method

public Item getItemByCategoryId(String categoryId) {
    Item item = null;
    try {
        item = mgr.find(Item.class, categoryId); // for single record
    } catch (Exception e) {
        e.printStackTrace();
    }
    return item;
}

      

or



Get all posts based on categoryId

// for all the records which are mapped by categoryId
public List<Item> getItemListByCategoryId(String categoryId) {
    List<Item> itemsList = null;
    try {
        String sqlQuery = "SELECT b FROM Item AS b WHERE b.categoryId=:catId";
        Query query = mgr.createQuery(sqlQuery);
        query.setParameter("catId", categoryId);
        itemsList = query.getResultList();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return itemsList;
}

      

0


source


Why are you using a String parameter for a parameter if it's a number?

Try:



String queryString="SELECT b FROM Item AS b WHERE b.categoryId=:catId";
Query q = mgr.createQuery(queryString);
Integer parameterValue=4;
q.setParameter("catId", parameterValue);
List<Item> itemList = (List<Item>) q.getResultList();

      

0


source







All Articles