根据这篇Difference between @OneToMany and @ElementCollection?的帖子,对于可嵌入类型,我应该首选@ElementCollection,对于实体,我应该首选@OneToMany。但是我可以使用@OneToMany额外设置orphanRemoval=true选项。如何使用@ElementCollection做到这一点?它暗示了吗?

最佳答案

这是隐含的。删除拥有的实体还将删除@ElementCollection上的所有数据。如果Collection尚未关闭,则将Collection设置为null或更改Session中的元素将导致更新。

官方文档here表示:

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

}

关于java - @ElementCollection是否暗示orphanRemoval?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46425395/

10-09 12:42