Thursday, June 07, 2018

Cara Menyimpan Perubahan "Collection" Pada Entity

Studi kasus
Pada JPA (Hibernate).

Entity A

@lombok.Data
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; 
    @Audited
    private String name; 
    @Audited
    @OneToMany(mappedBy="a", cascade=CascadeType.ALL, orphanRemoval=true)
    private  Set bs = new HashSet();
}

Entity B

@lombok.Data
public class B {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; 
    @Audited
    private String name; 
    @Audited
    @ManyToOne
    @JoinColumn(name = "id_a", nullable = false)
    private A a;
}

Kemudian kita buat instance dari class A dahulu dengan property bs tetap kosong. Lalu kemudian kita simpan. Setelah itu di method lain, instance class A itu kita panggil lalu kita setBs(setOfB) maka hasilnya akan muncul exception berikut:

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance

Solusinya,
kita bersihkan dulu lalu tambahkan semua element.
Jadi alih-alih melakukan ini:

A a = repositoryA.findOne(idA);
Set setOfB = buildSetOfB();
a.setBs(setOfB);
repositoryA.save(a);

lakukan ini:

A a = repositoryA.findOne(idA);
Set setOfB = buildSetOfB(); 
a.getBs().clear();
a.getBs().addAll(setOfB);
repositoryA.save(a);

Sumber inspirasi:
https://stackoverflow.com/questions/9430640/a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-ow

0 comments: