I have a simple OneToMany association between 2 object Parent & Child as shown below.
Parent Entity
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Version
private Long version;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
List<Child> children = new ArrayList<Child>();
....
}
Child entity
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Version
private Long version;
...
}
Following is my test which loads an existing parent adds a child and calls EntityManager.merge() on the parent.
@Test
public void testParent(){
Parent parent = (Parent) dao.loadParent(Parent.class, parentId);
Child c = new Child();
c.setName("c");
parent.getChildren().add(c);
dao.mergeEntity(parent);
Assert.assertNotNull(c.getId());
}
The assertion where primary key of the id is tested fails. I see the record being inserted correctly in the database along with the primary key auto assigned.
All my DAO calls are wrapped around transaction with propagation as Required.
EntityManager.merge(..)gets an instance and returns an instance that is managed. And in case of transient instances it returns a new instance (does not modify the original)So your
mergeEntity(..)method shouldreturn em.merge(entity)