gpt4 book ai didi

java - @ElementCollection 是否意味着 orphanRemoval?

转载 作者:行者123 更新时间:2023-11-30 10:25:01 26 4
gpt4 key购买 nike

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

最佳答案

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

官方文档here是这样说的:

2.8.1. Collections as a value type

Value and embeddable type collections have a similar behavior assimple value types because they are automatically persisted whenreferenced by a persistent object and automatically deleted whenunreferenced. If a collection is passed from one persistent object toanother, its elements might be moved from one table to another.
...
For collections of value types, JPA 2.0 defines the @ElementCollectionannotation. The lifecycle of the value-type collection is entirelycontrolled by its owning entity.

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

  @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(?, ?)
}

这是学生类:

@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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com