hibernate @ElementCollection是否暗示孤儿Removal?

ylamdve6  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(140)

根据这篇文章Difference between @OneToMany and @ElementCollection?,我应该选择@ElementCollection作为可嵌入类型,而@OneToMany用于实体。但是使用@OneToMany,我可以额外设置选项orphanRemoval=true。如何使用@ElementCollection执行此操作?这是在暗示什么吗?

pepwfjgg

pepwfjgg1#

这是隐含的。删除所属实体也会删除@ElementCollection上的所有数据。如果Session尚未关闭,则将Collection设置为空或更改Collection中的元素将导致更新。
这里的官方文件写道:
2.8.1。集合作为值类型
值和可嵌入类型集合的行为类似于简单值类型,因为它们在被持久对象引用时自动持久化,在未引用时自动删除。如果将集合从一个持久对象传递到另一个持久对象,则其元素可能会从一个表移动到另一个表。
..。
对于值类型的集合,JPA 2.0定义了@ElementCollection注解。值类型集合的生命周期完全由其所属实体控制。
我运行了这三个测试来测试它:

@Test
  public void selectStudentAndSetBooksCollectionToNull() {
    Student student = studentDao.getById(3L);
    List<String> books = student.getBooks();

    books.forEach(System.out::println);

    student.setBooks(null);

    em.flush(); // delete from student_book where student_id = ?
  }

  @Test
  public void selectStudentAndAddBookInCollection() {
    Student student = studentDao.getById(3L);
    List<String> books = student.getBooks();

    books.add("PHP Book");

    books.forEach(System.out::println);

    em.flush(); // insert into student_book(student_id, book) values(?, ?)
  }

  @Test
  public void selectStudentAndChangeCollection() {
    Student student = studentDao.getById(3L);
    List<String> newBooks = new ArrayList<>();

    newBooks.add("Rocket Engineering");

    newBooks.forEach(System.out::println);

    student.setBooks(newBooks);

    em.flush(); // delete from student_book where student_id = ?
    // insert into student_book(student_id, book) values(?, ?)
  }

这是Student类:

@Entity
@Table(name = "student")
public class Student {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "student_id", nullable = false, insertable = false, updatable = false)
  private Long id;

  @Column(name = "name", nullable = false)
  private String name;

  @ElementCollection
  @CollectionTable(
      name = "student_books",
      joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "student_id"))
  @Column(name = "book")
  private List<String> books = new ArrayList<>();

  // Getters & Setters

}

相关问题