简体   繁体   English

在多线程环境中初始化EntityManagerFactory

[英]Initializing EntityManagerFactory in a Multi-Threaded Environment

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. 处理持久化的类实现了runnable接口,我在run()方法中创建了EntityManagers。 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. 读完这篇文章后 ,我想知道在类构造函数中还是在静态初始化块中初始化EntityManagerFactory更好。

I assume that you use JPA in Java SE - not Java EE. 我假设您在Java SE中使用JPA,而不是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. 而且,我假设所有多个连接都针对同一个数据库...,并且我假设您不重用实例: EntityManager实例和可运行类实例都没有。

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. 如果假设正确,那么我宁愿在可运行类的静态初始化中或在作为单例实现的第二个类中初始化EntityManagerFactory

If you create EntityManagerFactory in the class constructor of the runnable class you have one factory per instance (that is per thread). 如果在可运行类的类构造函数中创建EntityManagerFactory ,则每个实例(每个线程)都有一个工厂。 This is is possible but unnecessary because you need only one EntityManagerFactory for multiple logical identical EntityManager instances. 这是可能的,但不是必需的,因为对于多个逻辑相同的EntityManager实例,您只需要一个EntityManagerFactory

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. 另一个问题是在哪里创建EntityManager本身:在类构造函数中(允许您在初始化线程中及早发现错误)或在run方法中。 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 ) 我个人更喜欢run -method,因为它允许您使用try/finally以相同的方法创建和关闭EntityManager

Warning: Be aware that you have no transactions across multiple threads. 警告:请注意,您没有跨多个线程的事务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM