我使用这个 native 查询来获取数据。
select c.id,c.name from customer c,information i 其中 i.status=1 and c.id=i.customerId
我使用下面的代码将对象列表转换为整数列表
public List<Integer> getAllIdsByGroupId(Integer groupId) throws Exception {
List<Object[]> list = repository.getAllIdsByGroupId(groupId);
List<Integer> ids = repository.mapIds(list);
return ids;
}
public List<Object[]> getAllIdsByGroupId(Integer groupId) {
Query query = entityManager.createNativeQuery("select c.id,c.name from customer c,information i where i.status=1 and c.id=i.customerId and c.groupId=:groupId");
query.setParameter("groupId", groupId);
List<Object[]> list = query.getResultList();
if (list == null || list.isEmpty()) {
return null;
}
return list;
}
public List<Integer> mapIds(List<Object[]> list) {
List<Integer> ids = new ArrayList<Integer>();
if (list != null && !list.isEmpty()) {
Integer id;
for (Object[] object : list) {
id = (object[0] != null ? (Integer) object[0] : null);
ids.add(id);
}
}
return ids;
}
查询检索一个带有 id 和 name 的列表。上面的代码无一异常(exception)地给出了输出。但是我需要只有 id 的列表。当我按如下方式从查询中删除 c.name 时
select c.id from customer c,information i 其中 i.status=1 and c.id=i.customerId
上面的代码失败并产生异常
java.lang.Integer cannot be cast to [Ljava.lang.Object;
有帮助吗?提前致谢。
最佳答案
问题出在类型转换上
改变
List<Object[]> list = query.getResultList();
到
<强> List<Object> list = query.getResultList()
它是您的代码尝试将整数转换为数组列表的对象列表。
List<Integer> list = query.getResultList()
如果您只是想获取 ID,也足够了
关于java - 如何在java中将对象的ArrayList转换为整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949860/