Skip to content

Instantly share code, notes, and snippets.

@daniel-shuy
Last active February 25, 2020 06:42
Show Gist options
  • Save daniel-shuy/34e88862155608f64bb5b9f96f72be7d to your computer and use it in GitHub Desktop.
Save daniel-shuy/34e88862155608f64bb5b9f96f72be7d to your computer and use it in GitHub Desktop.
JPA + CDI : @Inject EntityManager as a @RequestScoped bean
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Dependent
public class EntityManagerProducer {
@PersistenceContext(name = "persistence-unit") // name is Persistence Unit Name configured in persistence.xml
private EntityManager entityManager;
@Produces
@RequestScoped
EntityManager createEntityManager() {
return entityManager;
}
}
@daniel-shuy
Copy link
Author

EntityManager is not thread-safe.

This code snippet guarantees a new EntityManager is created/injected for each request.

Usage:

@Inject
EntityManager entityManager;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment