Ank*_*gal 0 java spring hibernate struts2
final List <Map<String , Object>> roleList;
final Map<Integer, String> roleMap=new HashMap<Integer, String>();
roleList = getSession()
.createQuery("select Id, Name from Emp where dept=:ref")
.setParameter("ref", "accounts")
.list();
for (Map<String, Object> map2 : roleList)
{
roleMap.put((Integer)(map2.get("Id")), (String)map2.get("Name"));
}
MappingBean.setRoleList(roleMap);
Run Code Online (Sandbox Code Playgroud)
上面的代码显示了类转换异常[Ljava.lang.Object; cannot be cast to java.util.Map.在Hibernate中有什么办法我们可以以List of Maps的形式获取数据吗?我roleList是地图的形式,我想设置roleList.
当你做出这样的选择时:
.createQuery("select Id, Name from Emp where dept=:ref")
Run Code Online (Sandbox Code Playgroud)
Hibernate默认返回a List<Object[]>,因为这是表示给定子字段的最安全的方式,它们决不会被绑定为具有相同的类型(因此,考虑最低的公共类Object).
但是,根据具体情况,您可以使用简单的迭代或使用配置将结果转换为映射.IMO 似乎是一种无用的练习,因为每条记录都将以一种key - Value成型的方式返回(即使它被表示为两个对象的数组).
通过这样做,直接(改变类型roleList)避免自己这样的开销:
for (Object[] role : roleList)
{
roleMap.put((Integer)role[0]), (String)role[1]);
}
Run Code Online (Sandbox Code Playgroud)
该Object[]由Hibernate返回尊重选定字段的顺序,这样,你的情况,指数0对应于Id与1到Name.
| 归档时间: |
|
| 查看次数: |
2163 次 |
| 最近记录: |