📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
EntityManager Interface Overview
EntityManager Interface - Class Diagram
EntityManager Interface Example
Steps to persist an entity object
Step 1: Creating an entity manager factory object
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE");
- Persistence - Persistence is a bootstrap class that 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 new application-managed EntityManager
Step 3: Initializing 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 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.
EntityManager Interface 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();
}
Comments
Post a Comment
Leave Comment