0

Hibernate 3x + Spring MVC 3x

PART-1

Generic Method

// getAll
@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> entityClass) throws DataAccessException {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);
return criteria.list();
}

Getting list in controller

 List<GenCurrencyModel> currencyList=pt.getAll(GenCurrencyModel.class);

Testing

System.out.println("Type: "+currencyList.get(0).getClass()); 
System.out.println("Value: "+((GenCurrencyModel)currencyList.get(0)).getId());

Result

Type: class com.soft.erp.gen.model.GenCurrencyModel
Value: 1

PART-2

Change in Generic Method [Using Projection]

 @SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<T> entityClass, String[] nameList) throws DataAccessException {
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(entityClass);

ProjectionList pl = Projections.projectionList();

for (int i=0; i<nameList.length; i++) {
    pl.add(Projections.property(nameList[i].toString()));   
}

criteria.setProjection(pl);

return criteria.list();
}

Getting List in controller

String []list={"id","isoCode"};
List<GenCurrencyModel> currencyList=pt.getAll(GenCurrencyModel.class,list);

Testing

System.out.println("Type: "+currencyList.get(0).getClass()); 
System.out.println("Value: "+((GenCurrencyModel)currencyList.get(0)).getId());

Result [java.lang.ClassCastException]

nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.soft.erp.gen.model.GenCurrencyModel]
  1. Why this class cast exception , because criteria.setProjection(pl) return criteria and then Criteria returning the same list.
  2. How to dynamically control this ?

update me !

Shahid Ghafoor
  • 2,991
  • 17
  • 68
  • 123

1 Answers1

0

You are setting a projection to request id and isoCode so the result is a list of Object array with id at index 0 and isoCode at index 1.

Try casting each result to Object[] and check the content of the array.

Manuel Darveau
  • 4,585
  • 5
  • 26
  • 36