Last active
February 25, 2020 06:42
-
-
Save daniel-shuy/34e88862155608f64bb5b9f96f72be7d to your computer and use it in GitHub Desktop.
JPA + CDI : @Inject EntityManager as a @RequestScoped bean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
EntityManager is not thread-safe.
This code snippet guarantees a new EntityManager is created/injected for each request.
Usage: