簡體   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