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]
- Why this class cast exception , because criteria.setProjection(pl) return criteria and then Criteria returning the same list.
- How to dynamically control this ?
update me !