InvalidDataAccessApiUsageException:未知实体:UserWithRoles

问题描述 投票:0回答:1

我正在使用Spring Security在Spring Boot项目上工作,当我编辑用户时,我得到一个InvalidDataAccessApiUsageException和一个回溯。以下是完整的消息:

2020-06-04 09:35:58.542错误13591 --- [nio-8080-exec-5] oaccC [。[。[/]。[dispatcherServlet]:Servlet [dispatcherServlet]中的Servlet.service()路径[]的上下文引发异常[请求处理失败;嵌套的异常是org.springframework.dao.InvalidDataAccessApiUsageException:未知实体:com.progeny.model.UserWithRoles;嵌套异常是java.lang.IllegalArgumentException:未知实体:com.progeny.model.UserWithRoles],根本原因是

这是控制器的代码:

// --------- 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";
}

感谢您的任何帮助。

java spring-boot spring-security spring-data-jpa
1个回答
0
投票

问题是“ SecurityContextHolder.getContext()。getAuthentication()。getPrincipal()”没有返回User对象,而是返回了UserWithRoles对象。 UserWithRoles用于设置currentuser变量。然后,代码尝试使用userRepo保存currentuser,这当然崩溃了,因为它不是User对象。这是一个UserWithRoles,不适合User的空间。

这是我所做的更改:

User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //1. Get the current user
User currentUser = new User(user);
© www.soinside.com 2019 - 2024. All rights reserved.