我有以下代码片段,当我执行时,我正在
java.lang.ClassCastException:[Ljava.lang.Object;无法投射到test.hr.Employee
代码:
Query query =
getEntityManager().createNamedQuery("Employee.findEmployees");
List<Employee> result = query.getResultList();
if (result != null) {
for (int i = 0; i < result.size(); i++) {
Employee emp = (Employee) result.get(i);
log.info("Employee =" +emp.getNumber());
}
JPQL:
select DISTINCT u.projectId,e.empNumber from Employee e LEFT JOIN
e.userProjectsList u JOIN u.projectMaster pm
where e.userNumber='SMITH'
如何摆脱这种异常?
答案 0 :(得分:1)
问题出在
Employee emp = (Employee) result.get(i);
试试这个
Object[] emp = (Object[]) result.get(i);
现在接下来你必须看到emp
对象
答案 1 :(得分:1)
实际上你的查询不会返回一个Employee而是一个Object数组(一个包含Project id和Employee id的对象数组),所以这里你有两个选择:
1 - 像这样更改您的JPQL
查询:
SELECT e from Employee e
2 - 或者更改您的代码以从对象中读取:
Query query =
getEntityManager().createNamedQuery("Employee.findEmployees");
List<Object[]> result = query.getResultList();
if (result != null) {
for (int i = 0; i < result.size(); i++) {
Object[] emp = (Object[]) result.get(i);
log.info("Employee =" +emp[0]);
}
修改强>
参考您需要执行的编辑:
for (int i = 0; i < result.size(); i++) {
Object[] emp = (Object[]) result.get(i);
log.info("Employee Number=" +emp[1]);
}