JPA EntityManager is at the core of Java Persistence API. Hibernate is the most widely used JPA implementation.

JPA EntityManager

  • One of the most important aspect of a program is connection with database. Database connection and transaction with database is considered as most expensive transaction. ORM is a very important tool in this regard. ORM helps in representing relations of database in terms of java objects.
  • ORM consists of two concepts object-oriented and relational programming.
  • Hibernate is an ORM framework where programmer describes the way objects are represented in database. Hibernate handles the conversion automatically.
  • Hibernate provides implementation of JPA interfaces EntityManagerFactory and EntityManager.
  • EntityManagerFactory provides instances of EntityManager for connecting to same database. All the instances are configured to use the same setting as defined by the default implementation. Several entity manager factories can be prepared for connecting to different data stores.
  • JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.

JPA EntityManager Methods

JPA EntityManager is supported by the following set of methods. For better readability, I have not mentioned method arguments.

  1. persist – Make an instance managed and persistent.
  2. merge – Merge the state of the given entity into the current persistence context.
  3. remove – Remove the entity instance.
  4. find – Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context, it is returned from there.
  5. getReference – returns and instance which is lazily fetched and will throw EntityNotFoundException when the instance is accessed for the first time.
  6. flush – Synchronizes the persistence context with the database.
  7. setFlushMode – set the flush mode for all the objects of the persistence context.
  8. getFlushMode – get the flush mode for all the objects of the persistence context.
  9. lock – Lock an entity instance that is contained in the persistence context with the specified lock mode type.
  10. refresh – it refreshes the state of the instance from the database also it will overwrite the changes to the entity.
  11. clear – Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
  12. detach – this is similar to the clear method, only addition is the entity which previously referenced the detached object will continue to do so.
  13. contains – it checks if the managed entity belongs to the current persistence context.
  14. getLockMode – get the current lock mode for entity instance.
  15. setProperty – set an entity manager property or hint.
  16. getProperties – get the properties and hints associated with the entity manager.
  17. createQuery – Create an instance of Query for executing a Java Persistence query language statement.
  18. createNamedQuery – Create an instance of Query for executing a Java Persistence named query language statement.
  19. createNativeQuery – Create an instance of Query for executing a native sql statement.
  20. createNamedStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.
  21. createStoredProcedureQuery – Create an instance of StoredProcedureQuery for executing a stored procedure in the database.
  22. joinTransaction – Indicate to the entity manager that a JTA transaction is active. This method should be called on a JTA application managed entity manager that was created outside the scope of the active transaction to associate it with the current JTA transaction.
  23. isJoinedToTransaction – it determines if the entityManager is linked to the current transaction.
  24. unwrap – Return an object of the specified type to allow access to the provider-specific API
  25. getDelegate – return the provider object for the entityManager.
  26. close – close an application-managed entityManager.
  27. isOpen – determine if the entityManager is open.
  28. getTransaction – Return the resource-level EntityTransaction object.
  29. getEntityManagerFactory – provides the entity manager factory for the entity manager.
  30. getCriteriaBuilder – Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.
  31. getMetamodel – Return an instance of Metamodel interface for access to the metamodel of the persistence unit.
  32. createEntityGraph – Return a mutable EntityGraph that can be used to dynamically create an EntityGraph.
  33. getEntityGraph – returns a named entityGraph

Let’s look at some of the methods through EntityManager example project.

Hibernate EntityManager Example

We will create a maven project for JPA Hibernate EntityManager example, below image illustrates different component of our Eclipse project.


I am using MySQL for database, below query will create our test table.

It’s a very simple table but suits for our example to showcase EntityManager usage.

Hibernate Maven Dependencies

We will have to include Hibernate and MySQL java driver dependencies in our pom.xml file. I am using Hibernate 5 with latest version of mysql-connector-java jar.

Hibernate persistence.xml

The most important part of using hibernate is to provide persistence.xml file. This xml holds the configuration for connecting to database.

  • hibernate.show_sql is used to tell hibernate to print sql queries into log files or console.
  • The most important configuration is provider class i.e.
    org.hibernate.jpa.HibernatePersistenceProvider. This is how Hibernate is hooked into our application to be used as JPA implementation.
  • There are properties to connect to your database and driver to use.
  • It is important to note that persistence.xml should be placed in the META-INF directory, as you can see from the project image.

Hibernate Entity Bean

We will now create an class that will correspond to the employee table created in the database. The employee class is declared as entity using the @Entity annotation.

Now it’s time to create our main program and run some queries using EntityManager methods.

  1. Persistence.createEntityManagerFactory will provide EntityManagerFactory instance using the persistence-unit that we have provided in the persistence.xml file
  2. entityManagerFactory.createEntityManager() will create EntityManager instance for us to use. Every time we call createEntityManager() method, it will return a new instance of EntityManager.
  3. entityManager.getTransaction().begin() method first pulls the transaction from current persistence context and then begins the transaction using begin() method.
  4. entityManager.persist(employee) is used to persist the employee object in the database.
  5. entityManager.getTransaction.commit() method is used to fetch the transaction and then to commit the same transaction. This will commit all the changes to database.
  6. entityManager.find() is used to find an entity in the database using primary key.
  7. If you want to write a custom query, we can use entityManager.createQuery() method for it. Important point to note here is that the createQuery() method will have name given in the entity class and not the actual table name.
  8. entityManager.remove() should be used only when we have to remove an entity from the database.
  9. entityManager.close() is used to close the entity manager. Similarly entityManagerFactory.close() is to close the EntityManagerFactory. We should close these resources as soon as we are done with them.

Below is the output produced from one sample run of above program.

Notice how the employee id is generated when it’s saved into database and then mapped back to the object. Also notice the sql queries getting printed into console. Note that Hibernate will create more logs but I haven’t put them here for maintaining readability.

That’s all for JPA EntityManager and it’s example with hibernate implementation. You can download the final Hibernate EntityManager example project from below link.

Reference: API Doc

By admin

Leave a Reply

%d bloggers like this: