TypedQuery getResultList返回对象Array而不是特定的类型。在for循环中迭代时获取ClassCastException

时间:2019-07-19 10:19:14

标签: java hibernate jpa

在Spring JPA Hibernate应用程序中,在获取resultList的同时,在增强的循环中迭代收到的ClassCastException时得到了List<Role>

在调试时,List<Role> roleList变量内的返回值显示为elementData = Object[10]而不是elementData = Role[10]

@Repository
class RoleDAOImpl{

    public List<Role> findAllRoles() {
        TypedQuery<Role> typedQuery = en.createQuery("SELECT r FROM Role r", Role.class);
        return typedQuery.getResultList();
    }   
}


@Service
class RoleServiceImpl{

    public List<RoleDTO> findAllRoles() {
        List<Role> roleList = roleDao.findAllRoles();

        List<RoleDTO> roleDTOList = RoleMapper.convertRoleListToRoleDTOList(roleList);

        // Code inside mapper
        for (Role role : roleList) { // ClassCastException: ...model.Role cannot be cast to ...model.Role
            System.out.println(role);
        }

        return roleDTOList;
    }
}

错误堆栈跟踪


java.lang.ClassCastException: com.vinit.Foodplazabootweb.model.Role cannot be cast to com.vinit.Foodplazabootweb.model.Role
    at com.vinit.Foodplazabootweb.service.RoleServiceImpl$$Lambda$376/386385529.accept(Unknown Source) ~[na:na]
    at java.util.ArrayList.forEach(Unknown Source) ~[na:1.8.0_51]
    at com.vinit.Foodplazabootweb.service.RoleServiceImpl.findAllRoles(RoleServiceImpl.java:35) ~[classes/:na]
    at com.vinit.Foodplazabootweb.controller.RoleController.getAllroles(RoleController.java:27) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_51]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_51]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870) ~[spring-webmvc-5.0.4.RELEASE.jar:5.0.4.RELEASE]
..

我希望从getResultList()的{​​{1}}返回的值为TypedQuery类型,而不是Role[]

调试屏幕截图。 Role Debug screenshot

Added example of Employee list, which shows <code>Employee[]</code> instead of <code>Object[]</code> 添加了“员工”列表示例,该列表显示Object[]而不是Employee[]

0 个答案:

没有答案