【问题标题】:Hibernate Projection throwing ClassCastException休眠投影抛出 ClassCastException
【发布时间】:2013-05-31 20:51:04
【问题描述】:

休眠 3x + Spring MVC 3x

第 1 部分

通用方法

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

在控制器中获取列表

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

测试

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

结果

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

第二部分

通用方法的变化[使用投影]

 @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();
}

在控制器中获取列表

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

测试

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

结果 [java.lang.ClassCastException]

nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.soft.erp.gen.model.GenCurrencyModel]
  1. 为什么这个类会抛出异常,因为 criteria.setProjection(pl) 返回条件,然后 Criteria 返回相同的列表。
  2. 如何动态控制这个?

更新我!

【问题讨论】:

    标签: hibernate criteria projection classcastexception hibernate-criteria


    【解决方案1】:

    您正在设置投影以请求 idisoCode,因此结果是 Object 数组列表,id 位于索引 0,isoCode 位于索引 1。

    尝试将每个结果转换为 Object[] 并检查数组的内容。

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 2015-07-17
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多