m suresh
m suresh

Reputation: 659

Get values from list object

I have code like this...

Query query = em.createQuery("select CM.salesAreaId, SM.salesAreaDesc, count(CM.salesAreaId), sum(CM.openBal), " +
                    "sum(CM.netSales) from CustomerMaster CM, SalesAreaMaster SM where CM.salesAreaId=SM.salesAreaCode and CM.companyId=SM.companyId" +
                    " and CM.companyId=:companyId group by CM.salesAreaId, SM.salesAreaDesc");
query.setParameter("companyId", companyId);
List list = query.getResultList();

From above code how can i get the list values?(list.get() values prints objects)

Upvotes: 1

Views: 7964

Answers (3)

Gab
Gab

Reputation: 8323

as JPA is an ORM spec, query result will necessary be a set of Objects. There is a workaround with hibernate if you're using this last as JPA implementation (see How to fetch hibernate query result as associative array of list or hashmap) but your code will be heavily coupled to hibernate then.
If you want to retrieve result as a resultSet (set of primitive values) you should use jdbc directly.

If your problematic is just to print the result in an human readable way you should override toString() method for all your JPA entities.

Upvotes: 1

clicky
clicky

Reputation: 865

You could use a for loop to iterate through, providing the index each time.

for (int i = 0; i < list.size(); i++)
{
    Object x = list.get(i);
    ...
}

http://docs.oracle.com/javase/6/docs/api/java/util/List.html#get(int)

Upvotes: 1

ccheneson
ccheneson

Reputation: 49410

Try this

Query query = em.createQuery("select CM.salesAreaId, SM.salesAreaDesc, count(CM.salesAreaId), sum(CM.openBal), " +
                    "sum(CM.netSales) from CustomerMaster CM, SalesAreaMaster SM where CM.salesAreaId=SM.salesAreaCode and CM.companyId=SM.companyId" +
                    " and CM.companyId=:companyId group by CM.salesAreaId, SM.salesAreaDesc");
query.setParameter("companyId", companyId);
List list = query.getResultList();
for(Object o : list) {
    Object[] obj = (Object[])o;

}

And the value of CM.salesAreaId should be in obj[0]

Upvotes: 2

Related Questions