3

I am using named query for returning List<?>. But now i have a requirement that i have to return a Map<key,value> so that i can filter the duplicates using the key..

I have a named query to return a List<String> for product names,

<named-query name="FETCH_ACTIVE_PRODUCTS_NAME" >
    <query>SELECT product.name FROM Product product
           WHERE product.name LIKE :name
    </query>
</named-query>

another named query to fetch a List<String> for product descriptions,

  <named-query name="FETCH_ACTIVE_PRODUCTS_DESC" >
    <query>SELECT product.desc FROM Product product
           WHERE product.desc LIKE :desc
    </query>
</named-query>

Another named query which fetches the product id's by product name

 <named-query name="FETCH_ACTIVE_PRODUCTS_ID_BY_NAME" >
    <query>SELECT product.id FROM Product product
           WHERE product.name LIKE :name
    </query>
</named-query>

Now I have to return a Map<Long,String> with key and value..key containing the product id and values containing the product name and description..the key should not contain duplicate values(i.e. duplicate product id's)..

Now my problem is how can i return a Map<Long,String> in named query..I've got no help from google... Any one have ideas about how to do this..

Lucky
  • 16,787
  • 19
  • 117
  • 151

2 Answers2

0

You can do this in your code (caller method) by looping through the list and adding the values to a map.

Code snippet

List <Product> products = new ArrayList<Product>();
// update products list by fetching from db.
Map<Long, String> productDesc = new HashMap<Long, String>();
for(Product prod : products) {
    if(productDesc.get(prod.getId() == null){
        productDesc.put(prod.toString());
    }
}

You can also put the snippet of iterating through the list and returning the map inside the product object itself if you have to use it in many places.

Arvind Sridharan
  • 3,885
  • 4
  • 29
  • 54
  • yeah i have this in my mind..this would be my second solution if i don't get a good one..its seems there is no direct method to fetch a map using hibernate named queries..i m feared if it can slow down performance..because i use these queries for search results.. – Lucky Jun 03 '13 at 06:34
  • @Lakshmanan - because hibernate does a mapping of your tabled result to object form, your query would never return a map. You don't need to be concerned about performance unless you are dealing with millions of rows (in which case you should refine your query/data perhaps) – Arvind Sridharan Jun 03 '13 at 06:36
0

Please look at this post. May be this will help you. For duplicate removal you can try nested query in another named query.

how to return Map<Key, Value> with HQL

Community
  • 1
  • 1
Harish Kumar
  • 528
  • 2
  • 15