merge is not working in the context of JPA

Viewed 41

This is my simple code:

 public static void main(String[] args) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("main");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();

        Team team1 = entityManager.find(Team.class, 0);
        System.out.println(entityManager.contains(team1));

        Team team2 = new Team();
        System.out.println(entityManager.contains(team2));

        entityManager.detach(team1);
        System.out.println(entityManager.contains(team1));

        entityManager.merge(team1);
        System.out.println(entityManager.contains(team1));

        transaction.commit();
        entityManager.close();
    }

The output is:

true
false
false
false

Look at the last false, it should be true because I merged that entity to the entity manager. any idea why it is giving false?

1 Answers

Entity manager will return new instance:

team1 = entityManager.merge(team1)

3.2.4.1 Merging Detached Entity State

The merge operation allows for the propagation of state from detached entities onto persistent entities managed by the EntityManager.

The semantics of the merge operation applied to an entity X are as follows:

  • If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
  • If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
  • If X is a removed entity instance, an IllegalArgumentException will be thrown by the merge operation (or the transaction commit will fail).
  • If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.
  • For all entities Y referenced by relationships from X having the cascade element value cascade=MERGE or cascade=ALL, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)
  • If X is an entity merged to X', with a reference to another entity Y, where cascade=MERGE or cascade=ALL is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
Related