An
EntityManager
is a part of the Java Persistence API (JPA) that manages the lifecycle of entities. The EntityManager interacts with the underlying database through the persistence context, ensuring that entities are synchronized with the database. The EntityManager
is used to create, read, update, and delete operations on entities.Purpose of @PersistenceContext
In Java EE or Spring applications, @PersistenceContext
automatically manages the lifecycle of the EntityManager
and ensures that the injected EntityManager
is associated with the correct persistence context (i.e., a set of managed entities).
When the @PersistenceContext
annotation is used:
- The container (like the Java EE server or Spring framework) manages the lifecycle of the
EntityManager
. - It injects an EntityManager instance tied to the current transaction or request.
- You don't need to manually create or close the
EntityManager
or handle its lifecycle explicitly
Key Methods of EntityManager
persist(Object entity)
: Makes an entity instance managed and persistent.find(Class<T> entityClass, Object primaryKey)
: Finds an entity by its primary key.merge(Object entity)
: Merges the state of the given entity into the current persistence context.remove(Object entity)
: Removes the entity instance.createQuery(String qlString)
: Creates a query instance for executing a JPQL query.getTransaction()
: Returns the resource-level transaction object.
Example Scenarios
Scenario 1: Basic CRUD Operations
Let’s consider a simple entity User
.
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
private String email;
// Getters and Setters
}
Persisting an Entity
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class UserService {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
public void createUser(User user) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
em.close();
}
}
Finding an Entity
public User findUser(Long id) {
EntityManager em = emf.createEntityManager();
User user = em.find(User.class, id);
em.close();
return user;
}
Updating an Entity
public void updateUser(User user) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
em.close();
}
Removing an Entity
public void deleteUser(Long id) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
User user = em.find(User.class, id);
if (user != null) {
em.remove(user);
}
em.getTransaction().commit();
em.close();
}
Scenario 2: Using JPQL Queries
Finding Users by Email
import javax.persistence.TypedQuery;
import java.util.List;
public List<User> findUsersByEmail(String email) {
EntityManager em = emf.createEntityManager();
TypedQuery<User> query = em.createQuery("SELECT u FROM User u WHERE u.email = :email", User.class);
query.setParameter("email", email);
List<User> users = query.getResultList();
em.close();
return users;
}
Scenario 3: Using Named Queries
You can define named queries in the User
entity.
import javax.persistence.NamedQuery;
@Entity
@NamedQuery(name = "User.findByName", query = "SELECT u FROM User u WHERE u.name = :name")
public class User {
@Id
private Long id;
private String name;
private String email;
// Getters and Setters
}
Using Named Queries
public List<User> findUsersByName(String name) {
EntityManager em = emf.createEntityManager();
TypedQuery<User> query = em.createNamedQuery("User.findByName", User.class);
query.setParameter("name", name);
List<User> users = query.getResultList();
em.close();
return users;
}
Conclusion
The EntityManager
is a powerful tool in JPA for managing the lifecycle of entities. It provides a rich set of methods for performing CRUD operations and querying the database. The examples above demonstrate how to use EntityManager
in different scenarios, from basic CRUD operations to using JPQL and named queries.
Post a Comment