When having simple parent-child relationship of
*Parent.java*
{code} @Entity public class Parent implements Serializable {
@Id private Integer id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval = true, cascade = CascadeType.ALL) private Set<Child> children = new HashSet<>();
// getters, setters, hashCode, equals omitted for brevity } {code}
and *Child.java*:
{code} @Entity public class Child implements Serializable {
@Id @ManyToOne(fetch = FetchType.LAZY, optional = false) private Parent parent;
@Id private String value;
// getters, setters, hashCode, equals omitted for brevity } {code}
then the following sequence of create-persist-detach-modify-merge:
{code} EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin();
Parent parent = new Parent(); parent.setId(10); Child child = new Child(); child.setParent(parent); child.setValue("old"); parent.getChildren().add(child);
entityManager.persist(parent); entityManager.flush(); entityManager.detach(parent); entityManager.getTransaction().commit(); entityManager.close();
// 'parent' is now detached; now let's change it and merge Child oldChild = parent.getChildren().iterator().next(); Child newChild = new Child(); newChild.setParent(parent); newChild.setValue("new"); parent.getChildren().add(newChild); parent.getChildren().remove(oldChild);
entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.merge(parent); entityManager.getTransaction().commit(); entityManager.close(); {code}
fails with
{code} Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "VALUE"; SQL statement: insert into Child (value, parent_id) values (?, ?) [23502-176] {code}
See also [this discussion|https://discourse.hibernate.org/t/merge-fails-with-composite-identifier-containing-association/191]. |
|