I ran into a problem that I have already solved, but still cannot explain the reason for this. The problem is with the modification of the object in the off state.
What I have:
Person β (one-two-many) β Address. A person has a lazy address list ( with orphanRemoval = true ).
What is the problem:
When I delete user addresses in the disconnected state, the old addresses are still present in the database, even after reconnecting the person to a new session, updating and committing. But after the merger of all the work fun .
What question:
What change merge (person) compared to update (person)?
What am I doing:
In the first session:
person.setAddresses(addressesList); transaction1.commit(); session1.close():
In the off state:
person.getAddresses().clear(); //addresses collection declares with orphanRemoval = true option. So all addresses should be deleted after collection is clear. Is it true in detached state?
In the second session:
session2.update(person);
Addition:
"Use update () if you are sure that the session does not contain an existing instance with the same identifier. Use merge () if you want to merge your changes at any time without regard to the state of the session. In other words, update () is usually the first the method you invoke in a new session, ensuring that re-linking your individual instances is the first operation to be performed. " (c) from the documentation .
But my session2 is fresh. In which case can the merge () method change?
SOURCE:
@Entity @Table(name = "person") public class Person{ @Id @SequenceGenerator(name = "person_sequence", sequenceName = "sq_person") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "person_sequence") @Column(name = "id") private int id; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true) @JoinColumn(name = "person_id") private List<FileInfo> files; //getter & setter } @Entity @Table(name = "address") @Inheritance(strategy= InheritanceType.JOINED) public class Address { @Id @SequenceGenerator(name = "adress_sequence", sequenceName = "sq_adress") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_sequence") @Column(name = "id") private long adressID; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "person_id") private Person person; }
source share