1

As in the title - why using CDI (Contexts and Dependency Injection) to inject an EntityManager (using Producer and @Inject annotation) is called a good practice? Why is it better than using @PersistenceContext annotation? I read that it is a preferred implementation but I cannot find why.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Adam
  • 884
  • 7
  • 29

1 Answers1

4

CDI is the standard technology for dependency injection in Java EE and it makes it convenient to create a method producer for the EntityManager then you can simply inject into your beans.

The @PersistenceContext annotation has a number of configurable elements (such as name) and you may not want to duplicate them all over the application, for example.

CDI injection is specially useful when you have multiple persistence units. Then you can take advantage of CDI qualifiers for injection:

public class Databases {

    @Produces @Users 
    @PersistenceContext(unitName="UserData")
    EntityManager userEntityManager;

    @Produces @Documents
    @PersistenceContext(unitName="DocumentData")
    EntityManager docDatabaseEntityManager;
}
@Inject @Users
EntityManager em;
@Inject @Documents
EntityManager em;
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Thank you for explanation! I read also that injecting via PersistenceContext is not thread safe - is it correct? – Adam Jun 01 '18 at 14:12
  • @Adam `EntityManager` is not thread safe. But you should read this [answer](https://stackoverflow.com/q/24643863/1426227) for further details. – cassiomolin Jun 01 '18 at 14:20
  • @Adam The question is, why do you need "thread-safeness". Normally the container controls what is running in parallel threads and which instances are shared. In that case you do not need to be concerned about threadsafety of injected EntityManager-Instances. Each thread will work using its own transaction and therefore its own EntityManager. – aschoerk Jun 05 '18 at 14:55