EntityManager entityManager = entityManagerFactory.createEntityManager(); try { // perform database operations using entityManager } finally { entityManager.close(); }
@PersistenceContext(unitName = "myPersistenceUnit") EntityManager entityManager; public void myMethod() { // perform database operations using entityManager entityManager.close(); }In this example, the EntityManager instance is injected using the @PersistenceContext annotation. The close() method is called explicitly within a method of the class that contains the fields annotated with @PersistenceContext. The javax.persistence.EntityManager close() method is part of the Java Persistence API (JPA) library, which is typically included in the javax.persistence package.