JPA - EntityManager.merge Examples

Code Snippets JPA JAVA EE 

    private static void updateEmployee(Employee employee) {
System.out.println("-- merging employee --");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(employee);
em.getTransaction().commit();
print("Employee merged", employee);
}
Original Post




    private static List<Phone> mergeAndGetPhoneList(Person person) {
EntityManager em = emf.createEntityManager();
person = em.merge(person);
List<Phone> phoneList = person.getPhoneList();
em.close();
return phoneList;
}
Original Post




    private static void findDetachAndMergeEntity() {
EntityManager em = entityManagerFactory.createEntityManager();
Employee employee = em.find(Employee.class, 1);
System.out.println("after find(): " + em.contains(employee));
em.detach(employee);
System.out.println("after detach(): " + em.contains(employee));
employee = em.merge(employee);
System.out.println("after merging(): " + em.contains(employee));
em.close();
}
Original Post




    private static void findByRefDetachAndMerge() {
EntityManager em = entityManagerFactory.createEntityManager();
Employee employee = em.getReference(Employee.class, 1);
System.out.println("after getReference(): " + em.contains(employee));
em.detach(employee);
System.out.println("after detach(): " + em.contains(employee));
employee = em.merge(employee);
System.out.println("after merge(): " + em.contains(employee));
em.close();
}
Original Post




See Also