java.lang.ClassCastException:无法将java.lang.String强制转换为com.security.model.UserRequest

时间:2019-02-21 19:32:07

标签: java jpa

如下所示,使用JPA查询从数据库中检索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)

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:2)

您的查询将返回String的列表,而您希望获得UserRequest的列表。如下更改查询应该可以完成这项工作:

@Query("SELECT req from User u, UserRequest as req WHERE u.username = req.userRequestName and req.userRequestRole= '4' and u.active=true")

答案 2 :(得分:1)

您在@Query里面写过

SELECT req.supervisorEmail from User u, UserRequest as req...

我假设supervisorEmailVARCHARCHAR表列。
您只提取了一个String列。

如果您需要UserRequest,则需要

SELECT req from User u, UserRequest as req...