繁体   English   中英

如何在 object 列表中找到 object 并通过其 ID 保存 - SpringBoot

[英]How to find an object in an List of object and save by its ID - SpringBoot

我有一个包含bookId的 Book 对象列表。

我必须传递 Book 对象列表并将每个 object 保存在数据库中的行中。

列表如下所示:

[
    {
        "bookId": 2
    },
    {
        "bookId": 3
    },
    {
        "bookId": 2
    },
    {
        "bookId": 3
    }
]

有人可以指导我代码应该是什么样子吗?

我开始这样的事情:

public void addMultipleRents(List<RentDto> rentDtoList, long userId){
        List<Rent> rentList = Arrays.asList(modelMapper.map(rentDtoList, Rent.class));

        RentDto rentDto = new RentDto();
        
        User user = userRepository.findById(userId)
                .orElseThrow(()-> new UserNotFoundException("User with id: " + 
        rentDto.getUserId() + " is not found"));
         
        List<Rent> rent = new ArrayList<>();

        for(Rent r  : rentList){
            r.setRentStart(LocalDateTime.now());
            r.setUser(user);
            r.setBook(book);
            rent.add(r);
        }

        rentRepository.saveAll(rentList);
}

租.java

public class Rent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private LocalDateTime rentStart;
    private LocalDateTime rentEnd;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "book_id", referencedColumnName = "id")
    private Book book;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    private User user;

}

RentDto.java

公共 class RentDto {

private Long rentId;

private Long userId;

private Long bookId;

private String userFirstName;

private String userLastName;

private String bookTitle;

private LocalDateTime rentStart;

private LocalDateTime RentEnd;

}

但我收到r.setBook(book);的错误。

The given id must not be null!

总结评论的踪迹:

您可以自己迭代 DTO 列表并为每个 DTO 创建一个Rent实体,而不是依赖modelMapper (无论 class 是什么)。 然后,您将它们放入一个列表并保存该列表,就像您已经在做的那样。

伪代码可能是这样的(简化):

User user = userRepo.getById(userId); //get the user for all rentals

List<Rent> rentList = new ArrayList<>(rentDtos.size()); //you already know the list size you're expecting
for( RentDTO dto : rentDtos) {
  Book book = bookRepo.getById( dto.getBookId() ); //the book for the one rental
  Rent rent = new Rent(); //create a new rent
  ... //set user, book and rent time here
  rentList.add(rent);
}

rentRepository.saveAll(rentList);

请注意,此(伪)代码并不意味着可编译、快速或处理所有可能的错误,而是让您开始。

一个明显的改进是首先收集一组书籍 ID,为这些 ID 加载所有书籍(例如,作为Map<Long, Book> ),然后将书籍分配给来自该 map 的Rent实体。 不过,我会把它留给你作为练习。

最后一个建议:由于您是初学者,因此您应该首先掌握基础知识,然后再深入了解复杂的框架,例如 Spring 等。这些框架利用依赖注入、对象关系映射等概念,这将如果您仍然缺少基础知识,则很难正确理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM