java.lang.ClassCastException:java.lang.String

我正在UserRequest使用 JPA Query 从 DB 中检索对象,如下所示。


@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.controller.UserController.getSupervisorEmailIds 中转换为 com.cat.pscs.security.model.UserRequest(UserController.java:320)


烙印99
浏览 141回答 3
3回答

一只名叫tom的猫

您的查询返回列表String,而您希望获得列表UserRequest。如下更改查询应该可以完成这项工作:@Query("SELECT&nbsp;req&nbsp;from&nbsp;User&nbsp;u,&nbsp;UserRequest&nbsp;as&nbsp;req&nbsp;WHERE&nbsp;u.username&nbsp;=&nbsp;req.userRequestName&nbsp;and&nbsp;req.userRequestRole=&nbsp;'4'&nbsp;and&nbsp;u.active=true")

人到中年有点甜

您确定下面的行返回 UserRequestList 吗?我认为它返回字符串列表List<UserRequest>&nbsp;supervisorEmailIds&nbsp;=&nbsp;userService.getSupervisorEmailIds();只需更改返回 UserRequest 对象列表的 sql 查询。

阿晨1998

你在里面@Query写SELECT&nbsp;req.supervisorEmail&nbsp;from&nbsp;User&nbsp;u,&nbsp;UserRequest&nbsp;as&nbsp;req...我想supervisorEmail是一个VARCHAR或CHAR表列。您只提取一String列。如果你想要UserRequest(S),你需要SELECT&nbsp;req&nbsp;from&nbsp;User&nbsp;u,&nbsp;UserRequest&nbsp;as&nbsp;req...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java