简体   繁体   English

Spring Data JPA + Hibernate 保存子实体而不先找到父实体

[英]Spring Data JPA + Hibernate save children entities without finding parent firstly

In my opinion, if you want to save children entities, you must find their parent firstly.在我看来,如果你想保存子实体,你必须首先找到它们的父实体。 But it's not true.但事实并非如此。 Following is an example.下面是一个例子。

Person table人表

public class Person {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  
  @OneToMany(mappedBy = "person", fetch = FetchType.LAZY)
  private List<Book> books;
}

Book table书桌

public class Book {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  @JoinColumn(name = "person_id", nullable = false)
  private Person person;
}

BookRepository书库

public interface BookRepository extends CrudRepository<Book, Long> {}

persist process坚持过程

// the person(id=1) is in the database.
Person p = new Person();
p.setId(1);

Book book = new Book();
book.setPerson(p);
book.setName("book");

bookRepository.save(book); // no error throws

I want to know why the last statement is success.我想知道为什么最后一个语句是成功的。 The person instance is created manually and is not retrieved from database by Spring Data JPA, I think it means the state of person instance is transient. person 实例是手动创建的,不是 Spring Data JPA 从数据库中检索的,我认为这意味着 person 实例的状态是瞬态的。

Based on your logic Book and person are new then you have to create those objects.根据您的逻辑书和新人,您必须创建这些对象。 Why you think it should come from database.为什么你认为它应该来自数据库。 If you want retrieve the user by findbyId then set the newly created book in List and save the user object behind the scenes it will do the updation in the database for that user.如果您想通过 findbyId 检索用户,然后在 List 中设置新创建的书并在幕后保存用户对象,它将为该用户在数据库中进行更新。

您可以使用personRepository.getOne(1)它将返回一个 id 为 1 的人的代理。然后将此对象设置为书上的人将执行您要查找的操作。

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

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