When having simple parent-child relationship of
Parent.java
@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 }
and Child.java:
@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 }
then the following sequence of create-persist-detach-modify-merge:
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();
fails with
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "VALUE"; SQL statement: insert into Child (value, parent_id) values (?, ?) [23502-176]