Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Id not being set when calling EntityManager.merge()

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.

like image 728
Rakesh Avatar asked Jun 01 '11 07:06

Rakesh


People also ask

What does EntityManager merge do?

EntityManager. merge() can insert new objects and update existing ones.

How does merge work in JPA?

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.

How does EntityManager work in JPA?

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.

Is hibernate EntityManager thread safe?

The EntityManagerFactory instances, and consequently, Hibernate's SessionFactory instances, are thread-safe.


1 Answers

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)

like image 163
Bozho Avatar answered Oct 07 '22 01:10

Bozho