2017-09-26 8 views
1

この投稿によるとDifference between @OneToMany and @ElementCollection?埋め込み可能なタイプの場合は@ElementCollection、エンティティの場合は@OneToManyが好ましいはずです。しかし、@OneToManyを使用すると、オプションorphanRemoval=trueを追加設定できます。 @ElementCollectionでどうすればいいですか?それはどういう意味ですか?@ ElementCollectionはorphanRemovalを意味しますか?

答えて

0

これは暗示されています。所有エンティティを削除すると、@ElementCollectionのすべてのデータも削除されます。 Collectionをヌルに設定するかCollectionの要素を変更すると、Sessionがまだ閉じていなければ更新が行われます。

公式ドキュメントhereはこれを言う:

2.8.1。彼らは 永続オブジェクトが参照するときに自動的に持続し、自動的に削除されるため、値型

値と、埋め込み型のコレクションとしてコレクションが シンプルな値型と同様の動作をしたときに 参照されていません。 1つのコレクションが1つの永続オブジェクトから別のグループに に渡された場合、その要素はあるテーブルから別のテーブルに移動される可能性があります。
...
JPA 2.0は、値タイプのコレクションの場合、@ ElementCollection アノテーションを定義します。 value-typeコレクションのライフサイクルは、所有エンティティによって完全に制御されます( )。

私はそれをテストするために、これらの3つのテスト実行しました:これはStudentクラスです

@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 

} 
+0

しかし、それはorphanRemovalがすべてに約あるではありません。もちろん、親を削除した場合、子供はカスケードの方法で削除されますが、それがもはや利用できないように参照を失うだけの場合(たとえば、nullに設定することによって)、子供にはどうなりますか? –

+1

はい、 '@ ElementCollection'フィールドには暗黙のうちに' Cascasde.ALL' + 'orphanRemoval = true' –

関連する問題