Issue
I am trying to update list of data that is foreignkey in another table.
Scenario:
I have class A:
public class A{
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "A", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<B> b;
}
i have also another class B:
public class B {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "a_id", nullable = false)
private A a;
}
My goal is: to update list of b in perfect way.
Example:
i have this id list for table B :
id | name | a_id |
---|---|---|
1 | n1 | 1 |
2 | n2 | 1 |
3 | n3 | 1 |
4 | n4 | 2 |
5 | n5 | 1 |
6 | n6 | 3 |
I have this list to update :
[n3,n9,n2,n7,n8]
this list must be updated for a_id = 1 so in this case i have 2 things to do:
first : adding n7, n8, n9 (with a_id = 1)
second: remove n1, n5 (because they are not included in the list above)
My expected output :
id | name | a_id |
---|---|---|
2 | n2 | 1 |
3 | n3 | 1 |
4 | n4 | 2 |
6 | n6 | 3 |
7 | n7 | 1 |
8 | n8 | 1 |
9 | n9 | 1 |
How can we achieve this result in the best way?
Solution
Use the following mapping and just merge/save the A
entity, and Hibernate will take care of removing/persisting/updating.
public class A {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(orphanRemoval = true, cascade = CascadeType.ALL)
@JoinColumn(name = "a_id", nullable = false)
private List<B> b;
}
public class B {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
}
If you want to keep the a
association in B
, then you will have to do the persist/update/remove manually, by calling EntityManager.persist
/EntityManager.merge
/EntityManager.remove
respectively for the various B
entities.
Answered By - Christian Beikov
Answer Checked By - Marie Seifert (JavaFixing Admin)