在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[]
。