I am persisting entities over multiple connections to a database. The class handling the persisting implements the runnable interface, and I create the EntityManagers in the run() method. After reading this, I want to know if it is better to initialize the EntityManagerFactory in the class constructor or in a static initialization block.
- I think one needs to inject the EntityManagerFactory then make a new EntityManager in each thread, since your application needs to be thread-safe as well, that's the solution I used for a similar requirement.Marcelo Tataje– Marcelo Tataje2013-02-27 23:34:02 +00:00Commented Feb 27, 2013 at 23:34
1 Answer
I assume that you use JPA in Java SE - not Java EE. Moreover I assume that you have a class which handles the persisting of your entities - and that you mean this class when you are asking for class constructor or static initilization. Moreover I assume that all of your multiple connections targets the same database ... and I assume that you do not reuse your instances: neither your EntityManager instances nor your runnable class instances.
If the assumtions are correct then I would prefer to initialize the EntityManagerFactory either in a static initilization of your runnable class or in a second class which is implemented as singleton.
If you create EntityManagerFactory in the class constructor of the runnable class you have one factory per instance (that is per thread). This is is possible but unnecessary because you need only one EntityManagerFactory for multiple logical identical EntityManager instances.
Another question is where to create the EntityManager itself: in the class constructor (allows you to catch errors early in the initilization thread) or in the run-method. Personally I would prefer the run-method because it allows you to create and close the EntityManager in the at the same method using try/finally)
Warning: Be aware that you have no transactions across multiple threads.