0

I'm reading through the JAVA EE7 Persistence chapter, and all I see is that you need to create a EntityManagerFactory in order to create an EntityManager.

All the method calls seem to be done by the EntityManager, so why is there a need to create a EntityManagerFactory? What exactly does it do?

I tried finding the answer here and on the internet but to no avail.

Thanks.

BartKrul
  • 577
  • 1
  • 8
  • 21
  • See http://stackoverflow.com/questions/1310087/injecting-entitymanager-vs-entitymanagerfactory. Basically, When EntityManager is not injected by the container, you need a factory to instantiate it. – Leo May 24 '16 at 18:06

1 Answers1

1

Read up on the Factory design pattern in general. The answer linked in Leo's comment (https://stackoverflow.com/a/1310415/2762475) links and explains some documentation. That's a good place to start. Dependency injection in general can be extremely useful, but perhaps is outside your use case for EntityManager.

IMO, the key thing to understand here is the purpose of the factory: as a consumer of the product (in this case, the Manager), all you have to do is order one from the factory and they will give you the right one. Compare this with a big pile of products that you can grab from willy-nilly. This is fine if you're the only one grabbing, but as soon as competition for resources arises, you can't ensure you get the exact object that you need, even if you know what it looks like.

Community
  • 1
  • 1
Allan L.
  • 26
  • 2