0

I am using hibernate to get a result like this,

project_id - 123 , 111 , 134
Count - 2 , 5 ,6

Here is my Dao layer -

@Query("SELECT project_id,COUNT(*) FROM lead_master WHERE vendor_id = ?1 and source = 'share' group by project_id ")
List<Map<String,Object>> getProjectLead(userId); 

Output - I want the List of Map where the project_id should be the key and the count should be the object associated with that key.so it will be like -

123 - 2
111 - 5
134 - 6

3
  • this one either use List<Object[]> or projection baeldung.com/… Commented Jan 23, 2020 at 11:35
  • but i want to get a mapped list that will be a pair of project id and count Commented Jan 23, 2020 at 11:43
  • even Object[] also has same information project_id at 0 and count at 1 indexes Commented Jan 23, 2020 at 11:45

2 Answers 2

1

You can use a ResultTransformer for that:

(List<Map<String, Object>>) entityManager.createNativeQuery(
    "SELECT project_id, COUNT(*) FROM lead_master WHERE vendor_id = :userId and source = 'share' group by project_id "
)
    .setParameter("userId", userId)
    .unwrap(org.hibernate.query.Query.class)
    .setResultTransformer(
        new ResultTransformer() {
            @Override
            public Object transformTuple(Object[] tuple, String[] aliases) { // 2.
                return new HashMap.of((String) tuple[0], tuple[1]);
            }

            @Override
            public List transformList(List collection) {
                return collection;
            }
        }
    )
    .getResultList();
Sign up to request clarification or add additional context in comments.

Comments

0

I did simply iterate the list of map from jpa then get the values of project_id,count and then stored the key and values using new map.I hope it will help you.

Map<String,Object> map=new HashMap<>();
        List<Map<String, Object>> res = samplerepository.getProjectLead(userId);
        res.forEach(action -> {
            String key = (String) action.get("project_id");
            BigInteger value = (BigInteger) action.get("count");                
            map.put(key, value);
        });
        System.out.println("size : " + map.toString());   

        Output will be :: {111=5, 123=2, 134=6}

Thanks,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.