user222 user222 - 1 year ago 85
Java Question

how to fix java.lang.ClassCastException: java.util.ArrayList while getting values from DB

I am working on spring application. I am connecting to database using HibernateDaoSupport class in spring framework.

Below is my java code:

public class MyTableDAOHibernateImpl extends HibernateDaoSupport implements MyTableDAO{
public String getDBValues() throws DataLayerException {
String value = "";
Map<String, String> map = null;
try {
map = (HashMap<String,String>)getHibernateTemplate()
.find("select mt.fname,mt.lname from MyTable as mt where aid= '29983L"' ");
System.out.println("MAP elements : " + map);
if (map != null && !map.isEmpty()) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry);
value = (String) pair.getValue();
System.out.println("name" + value);
} catch (final DataAccessException dae) {
throw new DataLayerException(dae);
return value;

The above code is throwing the below exception:

Encountered serious error building result : java.lang.ClassCastException: java.util.ArrayListjava.lang.ClassCastException: java.util.ArrayList

Please suggest, in my code getHibernateTemplate() is returning a
.As per my requirement i need to store the value returned from database in key,value pair using HashMap. Unable to trace the
. Please advice.

Answer Source

getHibernateTemplate().find(...) returns List<?> of objects not Map<K,V>

You have to change to list in your code

List<Object[]> rs = ( List<Object[]> ) getHibernateTemplate().find("select mt.fname,mt.lname from MyTable as mt where aid= '29983L'");