@ElementCollection是否意味着orphanRemoval?

时间:2017-09-26 11:33:39

标签: java hibernate orm

根据这篇文章Difference between @OneToMany and @ElementCollection?,我希望@ElementCollection用于可嵌入类型,@OneToMany用于实体。但是使用@OneToMany我可以另外设置选项orphanRemoval=true。如何使用@ElementCollection执行此操作?它意味着什么?

1 个答案:

答案 0 :(得分:0)

暗示。删除拥有实体也会删除$ awk -F '|' 'NR==3{for(i=1;i<=NF;i++)printf("Column-%d = $%d = %s\n",i,i,$i)}' infile Column-1 = $1 = a Column-2 = $2 = 50 Column-3 = $3 = Need to improve 上的所有数据。如果@ElementCollection尚未关闭,则Collection设置为空或更改Collection中的元素会导致更新。

官方文档here说明了这一点:

  

2.8.1。集合作为值类型

     

Value和embeddable类型集合具有类似的行为   简单的值类型,因为它们在自动持久化时   由持久对象引用并在自动删除时   未引用。如果集合从一个持久对象传递到   另外,它的元素可能会从一个表移动到另一个表。   
...   
  对于值类型的集合,JPA 2.0定义了@ElementCollection   注解。 value-type集合的生命周期完全是   由其拥有的实体控制。

我运行了这三个测试来测试它:

Session

这是 @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
相关问题