JPA - EntityManager.detach Examples

Code Snippets JPA JAVA EE 

    private static void findAndDetachEntity() {
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));
em.close();
}
Original Post




    private static void findByReferenceAndDetachEntity() {
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));
em.close();
}
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
   private static void persistEmployee() {
Employee employee = new Employee("Joe", "IT",
Phone.cell("111-111-1111"), Phone.work("222-222-2222"));
entityManager.getTransaction().begin();
entityManager.persist(employee);
entityManager.getTransaction().commit();
//detach to remove it from entityManager cache
entityManager.detach(employee);
}
Original Post




See Also