Close

JPA - Persisting Entities

[Last Updated: Dec 1, 2017]

A new entity instance becomes both managed and persistent by invoking the EntityManager#persist() method on it.

A a cascading relationship (specified via cascade=PERSIST or cascade=ALL) will also be persisted by this operation operation.

As a result of this operation the target entity is marked to be entered into the database at transaction commit or as a result of the EntityManager#flush() operation, but the new entity will only be visible to other EntityManager instances or other database clients at transaction commit.

Example

The Entity

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String department;
    .............
}

Persisting entity

public class ExampleMain {

    public static void main(String[] args) {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("example-unit");
        try {
            persistEntity(emf);
            loadEntities(emf);
        } finally {
            emf.close();
        }
    }

    private static void persistEntity(EntityManagerFactory emf) {
        System.out.println("-- Persisting Employee entity --");
        EntityManager em = emf.createEntityManager();

        Employee employee = new Employee();
        employee.setName("Maria Dorsey");
        employee.setDepartment("Admin");

        em.getTransaction().begin();
        logPersistentStatus("before persisting", employee, em);
        em.persist(employee);
        logPersistentStatus("after persisting", employee, em);
        em.getTransaction().commit();
        em.close();
    }
    .............
    private static void logPersistentStatus(String msg, Employee employee, EntityManager em) {
        System.out.printf("-- %s --%n", msg);
        System.out.println("employee#id: " + employee.getId());
        System.out.println("EntityManager#contains(): " + em.contains(employee));
    }
    .............
}
-- Persisting Employee entity --
-- before persisting --
employee#id: null
EntityManager#contains(): false
-- after persisting --
employee#id: 1
EntityManager#contains(): true
-- Loading Employee --
Object: Employee{id=1, name='Maria Dorsey', department='Admin'}

Rolling back after persist()

public class ExampleMain2 {

    public static void main(String[] args) {
        EntityManagerFactory emf =
                Persistence.createEntityManagerFactory("example-unit");
        try {
            persistEntity(emf);
            loadEntities(emf);
        } finally {
            emf.close();
        }
    }

    private static void persistEntity(EntityManagerFactory emf) {
        System.out.println("-- Persisting Employee entity --");
        EntityManager em = emf.createEntityManager();

        Employee employee = new Employee();
        employee.setName("Maria Dorsey");
        employee.setDepartment("Admin");

        em.getTransaction().begin();
        logPersistentStatus("before persisting", employee, em);
        em.persist(employee);
        logPersistentStatus("after persisting", employee, em);
        System.out.println("-- rolling back --");
        em.getTransaction().rollback();

        System.out.println("-- persisting second employee --");
        Employee employee2 = new Employee();
        employee2.setName("Tim Don");
        employee2.setDepartment("Sales");

        em.getTransaction().begin();
        logPersistentStatus("before persisting", employee2, em);
        em.persist(employee2);
        logPersistentStatus("after persisting", employee2, em);
        em.getTransaction().commit();
        em.close();
    }
    .............
}
-- Persisting Employee entity --
-- before persisting --
employee#id: null
EntityManager#contains(): false
-- after persisting --
employee#id: 1
EntityManager#contains(): true
-- rolling back --
-- persisting second employee --
-- before persisting --
employee#id: null
EntityManager#contains(): false
-- after persisting --
employee#id: 2
EntityManager#contains(): true
-- Loading Employee --
Object: Employee{id=2, name='Tim Don', department='Sales'}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.10.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

EntityManager#persist Example Select All Download
  • jpa-persisting-entities
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also