DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Fluent-API: Creating Easier, More Intuitive Code With a Fluent API
  • The Magic of Spring Data
  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I

Trending

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Segmentation Violation and How Rust Helps Overcome It
  • Chaos Engineering for Microservices
  • The Modern Data Stack Is Overrated — Here’s What Works
  1. DZone
  2. Data Engineering
  3. Databases
  4. JPA EntityManagerFactory Interface With Example

JPA EntityManagerFactory Interface With Example

You can support instantiation of EntityManager instances in Java with this interface!

By 
Ramesh Fadatare user avatar
Ramesh Fadatare
·
Dec. 14, 18 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
87.7K Views

Join the DZone community and get the full member experience.

Join For Free

The main role of an EntityManagerFactory instance is to support instantiation of EntityManager instances. An EntityManagerFactory is constructed for a specific database, and by managing resources efficiently (e.g. a pool of sockets), it provides an efficient way to construct multiple EntityManager instances for that database.

The instantiation of the EntityManagerFactory itself might be less efficient, but it is a one-time operation. Once constructed, it can serve the entire application. When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an EntityManagerFactory has been closed, all its entity managers are considered to be in the closed state.

EntityManagerFactory Interface — Class Diagram

This class diagram shows a list of APIs that the EntityManagerFactory Interface provides.

EntityManagerFactory Interface — Method Summary

Here the list of important methods EntityManagerFactory interface for your reference:

  • void addNamedEntityGraph(String graphName, EntityGraph entityGraph) — This method add a named copy of the EntityGraph to the EntityManagerFactory.
  • void addNamedQuery(String name, Query query) — This method is used to define the query, typed query, or stored procedure query as a named query such that future query objects can be created from it using the createNamedQuery or createNamedStoredProcedureQuery method.
  • void close() — This method close the factory, releasing any resources that it holds.
  • EntityManager createEntityManager() — This creates a new application-managed EntityManager.
  • EntityManager createEntityManager(Map map) — This method is used to create a new application-managed EntityManager with the specified Map of properties.
  • EntityManager createEntityManager(SynchronizationType synchronizationType) — This method is used to create a new JTA application-managed EntityManager with the specified synchronization type.
  • EntityManager createEntityManager(SynchronizationType synchronizationType, Map map) — This method used to create a new JTA application-managed EntityManager with the specified synchronization type and map of properties.
  • Cache getCache() — Access the cache that is associated with the entity manager factory (the "second level cache").
  • CriteriaBuilder getCriteriaBuilder() — Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.
  • Metamodel getMetamodel() — Return an instance of the Metamodel interface for access to the metamodel of the persistence unit.
  • PersistenceUnitUtil getPersistenceUnitUtil() — This method return the interface, providing access to utility methods for the persistence unit.
  • Map<String,Object> getProperties() — This method get the properties and associated values that are in effect for the entity manager factory.
  • boolean isOpen() — Indicates whether the factory is open.
  • T unwrap(Class cls) — Return an object of the specified type to allow access to the provider-specific API.

EntityManagerFactory Interface Example

Let's demonstrates the important methods of the  EntityManagerFactory Interface with an example. In this example, we will use the createEntityManager() method to create a new application-managed EntityManager.

Step 1: Creating an Entity Manager Factory Object

The  EntityManagerFactory interface present in the java.persistence package is used to provide an entity manager.

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE");


  • Persistence — The  Persistence is a bootstrap class, which is used to obtain an EntityManagerFactory interface.
  • createEntityManagerFactory() method — The role of this method is to create and return an EntityManagerFactory for the named persistence unit. Thus, this method contains the name of the persistence unit passed in the Persistence.xml file.

Step 2: Obtaining an Entity Manager From a Factory

EntityManager entityManager = entityManagerFactory.createEntityManager();


  • EntityManager — An EntityManager is an interface.
  •  createEntityManager() method — It creates a new application-managed EntityManager

Step 3: Intializing an Entity Manager

entityManager.getTransaction().begin();


  • getTransaction() method — This method returns the resource-level EntityTransaction object.
  • begin() method — This method is used to start the transaction.

Step 4: Persisting a Data Into the Relational Database

entityManager.persist(student); 


  • persist() — This method is used to make an instance managed and persistent. An entity instance is passed within this method.

Step 5: Closing the Transaction

entityManager.getTransaction().commit();


Step 6: Releasing the Factory Resources

entityManager.close();
entityManagerFactory.close();


  • close() — This method is used to release the factory resources.

Complete Example

private static void insertEntity() {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    Student student = new Student("Ramesh", "Fadatare", "rameshfadatare@javaguides.com");
    entityManager.persist(student);
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();
}

A good resource to learn JPA at JPA Tutorial - Java Persistence API

Further Learning:

  • JPA EntityTransaction Interface with Example

  • JPA CRUD Example

  • JPA EntityManager Interface with Example

  • Different Ways to Store JPA Entity Objects into a Database

  • Different Ways to Retrieve JPA Entity Objects from Database

  • Different Ways to Delete JPA Entity Objects from Database

  • Different Ways to Update JPA Entity Objects into a Database 

References

  • https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManagerFactory.html
  • JPA

Interface (computing) Relational database Database

Published at DZone with permission of Ramesh Fadatare. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Fluent-API: Creating Easier, More Intuitive Code With a Fluent API
  • The Magic of Spring Data
  • Designing a Blog Application Using Document Databases
  • Relational DB Migration to S3 Data Lake Via AWS DMS, Part I

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!