简体   繁体   English

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

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

I have a List of Book objects that contain bookId .我有一个包含bookId的 Book 对象列表。

I have to pass that List of Book objects and save each object in its row in database.我必须传递 Book 对象列表并将每个 object 保存在数据库中的行中。

List looks like this:列表如下所示:

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

Could someone guide me how the code should look like?有人可以指导我代码应该是什么样子吗?

I started something like this:我开始这样的事情:

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);
}

Rent.java租.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 RentDto.java

public class RentDto {公共 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;

} }

But I am getting error for r.setBook(book);但我收到r.setBook(book);的错误。 :

The given id must not be null!

To summarize the trail of comments:总结评论的踪迹:

Instead of relying on modelMapper (whatever the class is) you could iterate over the list of DTOs yourself and create a Rent entity for each of those.您可以自己迭代 DTO 列表并为每个 DTO 创建一个Rent实体,而不是依赖modelMapper (无论 class 是什么)。 You then put them into a list and save that list as you're doing already.然后,您将它们放入一个列表并保存该列表,就像您已经在做的那样。

The pseudo code for this could be something like this (simplified):伪代码可能是这样的(简化):

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);

Note that this (pseudo) code isn't meant to be compilable, fast or to handle all possible errors but to get you started.请注意,此(伪)代码并不意味着可编译、快速或处理所有可能的错误,而是让您开始。

One obvious improvement would be to first collect a set of book ids, load all books for those ids (eg as a Map<Long, Book> ) and then get the books to assignto the Rent entities from that map.一个明显的改进是首先收集一组书籍 ID,为这些 ID 加载所有书籍(例如,作为Map<Long, Book> ),然后将书籍分配给来自该 map 的Rent实体。 I'll leave that as an exercise for you though.不过,我会把它留给你作为练习。

One final advice: since you're a beginner you should first get a good grasp of the basics before getting too deep into complex frameworks such as Spring etc. Those frameworks make use of concepts like dependency injection, object-relational mapping etc. which would be too hard to understand correctly if you're still missing the basics.最后一个建议:由于您是初学者,因此您应该首先掌握基础知识,然后再深入了解复杂的框架,例如 Spring 等。这些框架利用依赖注入、对象关系映射等概念,这将如果您仍然缺少基础知识,则很难正确理解。

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

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