使用JPA Query从数据库中检索UserRequest对象,如下所示。

@Query("SELECT req.supervisorEmail from User u, UserRequest as req WHERE u.username = req.userRequestName and req.userRequestRole= '4' and u.active=true")
 public List<UserRequest> getSupervisorEmailIds();


正在具有UserRequest POJO类,如下所示。

public class UserRequest implements Identifiable<Long>, LazilyLoadable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private Long id;

@Column(name = "supervisor_email")
private String supervisorEmail;

@Column(name="user_request_name")
private String userRequestName;

@Column(name="user_request_role")
private String userRequestRole;

}


当尝试遍历UserRequest对象时,获取以下代码的ClassCastException

List<UserRequest> supervisorEmailIds = userService.getSupervisorEmailIds();
for(UserRequest s: supervisorEmailIds) { // throwing exception on this line.
if(s!=null) {
System.out.println("Printing -->"+s.getSupervisorEmail());
}
System.out.println("Null error");
}


以下是错误越来越严重。

2019-02-22 00:34:26,719 [http-9191-1] ERROR         com.cat.pscs.api.controller.BaseController:  83 - Unhandled exception while processing request for URL : http://localhost:9191/security/users/get-supervisor-emailids with exception : java.lang.String cannot be cast to com.cat.pscs.security.model.UserRequest


java.lang.ClassCastException:无法将java.lang.String强制转换为com.cat.pscs.security.model.UserRequest
    在com.cat.pscs.security.controller.UserController.getSupervisorEmailIds(UserController.java:320)

最佳答案

您确定下面的行返回UserRequestList吗?我认为它返回字符串列表

List<UserRequest> supervisorEmailIds = userService.getSupervisorEmailIds();


只需更改返回UserRequest对象列表的sql查询即可。

07-27 22:39