我正在使用 spring security 开发一个 Spring Boot 项目,当我编辑用户时,我得到一个 InvalidDataAccessApiUsageException 和一个回溯。以下是完整消息:
2020-06-04 09:35:58.542 错误 13591 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : servlet [dispatcherServlet] 的 Servlet.service()在路径 [] 的上下文中抛出异常 [请求处理失败;嵌套异常是 org.springframework.dao.InvalidDataAccessApiUsageException: 未知实体: com.progeny.model.UserWithRoles;嵌套异常是 java.lang.IllegalArgumentException: 未知实体: com.progeny.model.UserWithRoles] 其根本原因
这是 Controller 的代码:
// --------- ADD FRIEND (POST)------------
@PostMapping("/profile/friends/edit")
public String addFriend(@RequestParam long friendId, Model model) {
User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //1. Get the current user
User friend = usersRepo.getUserById(friendId);
System.out.println(currentUser.getFirstName());
System.out.println(friend.getFirstName());
if(friend.getFriends() == null){ // if there is no friends list -->
List<User> newFriends = new ArrayList<>(); // 1. Make a new friends list
friend.setFriends(newFriends); // 2. give the new friends list to User
}
if(currentUser.getFriends() == null){ // if there is no friends list -->
List<User> newFriends = new ArrayList<>(); // 1. Make a new friends list
currentUser.setFriends(newFriends); // 2. give the new friends list to User
}
// --------- ADD USER TO FRIEND-----------
currentUser.getFriends().add(friend);
System.out.println(currentUser.getFriends().get(0).getUsername());
// --------- ADD FRIEND TO USER------------
friend.getFriends().add(currentUser);
System.out.println(friend.getFriends().get(0).getUsername());
// --------- SAVE TO DB -----------
usersRepo.save(currentUser); // 3. save the list of users to the current users information
usersRepo.save(friend); // 3. save the list of users to the current users information
return "users/showConnections";
}
感谢任何帮助。
最佳答案
问题是“SecurityContextHolder.getContext().getAuthentication().getPrincipal()”不返回 User 对象,而是返回 UserWithRoles 对象。 UserWithRoles 用于设置 currentuser 变量。然后代码尝试使用 userRepo 保存当前用户,这当然会崩溃,因为它不是 User 对象。这是一个 UserWithRoles,不适合用户的空间。
这是我所做的更改:
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //1. Get the current user
User currentUser = new User(user);
关于java - 无效数据访问ApiUsageException : Unknown entity: UserWithRoles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62197486/