ClassCastException甚至在提供了类之后

时间:2015-06-02 10:56:23

标签: java jpa classcastexception

我有以下代码片段,当我执行时,我正在

  

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'

如何摆脱这种异常?

2 个答案:

答案 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]);
        }