将现有图书添加到现有用户

时间:2021-02-09 13:54:02

标签: java list

I have a problem with a piece of java code :
I am trying to add an existing book to an existing user and replace a book that the user already has .
The relation is manyToMany and it work's , but if a user has 2 books and i am trying to replace one with the other it delete's all books and add's the new one 

编辑:添加了代码 userDto 和 bookDto,我正在尝试将现有书籍添加到现有用户,但必须从集合中替换一本书并将另一本书留在那里

public User updateUser(UserDto userDto){
    User user = userRepository.findByFirstName(userDto.getFirstName());
    Set<Book> bookSet = user.getBookSet();
    List<Long> selectedIdList =userDto.getGetIdList();
    List<Long> bookIdList = bookSet.stream().map(Book::getId).collect(Collectors.toList());

    for(Long booksId : selectedIdList) {
        if (selectedIdList.contains(booksId)) {
            bookIdList.add(booksId);
        }else if(!selectedIdList.contains(booksId)){
            bookIdList.remove(booksId);
        }
    }

    return  user;
}
 @Data
public class UserDto {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private RoleType type;
    private Set<Book> bookSet;
    private List<Long> getIdList = new ArrayList<>();

    public RoleType getType() {
        return type;
    } 
    public void setType(RoleType type) {
        this.type = type;
    }
}
@Data
public class BookDto {
    private Long id;
    private String bookName;
}

0 个答案:

没有答案
相关问题