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() can insert new objects and update existing ones.
JPA's merge method copies the state of a detached entity to a managed instance of the same entity. Hibernate, therefore, executes an SQL SELECT statement to retrieve a managed entity from the database.
In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.
The EntityManagerFactory instances, and consequently, Hibernate's SessionFactory instances, are thread-safe.
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 should return em.merge(entity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With