本文介绍了如何创建一个线程安全的EntityManagerFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要进行一些数据库操作的应用程序。

I'm working on a application that needs to do some database operations.

我为EntityManagerFactory创建了一个静态变量,并在被调用的方法中对其进行了初始化应用程序

I created a static variable for EntityManagerFactory and Intialized it in the method that gets called by the application

 if (emf == null){
                    emf = Persistence.createEntityManagerFactory("example");
                }

try {
            em = emf.createEntityManager();
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }

这个线程安全吗?如果我在同步块中创建EntityManagerFactory,等待线程的数量会增加并使应用程序崩溃。

is this thread safe? if I create the EntityManagerFactory in a synchronized block, The number of waiting threads increases and crashes the application.

我查看了文档以查看Persistence.createEntityManagerFactory是否是线程保证没有任何成功。

I looked at the docs to see whether the Persistence.createEntityManagerFactory is thread safe without any success.

请指出正确的资源。

推荐答案

解决这个问题的简单方法是使用辅助类(la HibernateUtil )并初始化 EntityManagerFactory 在静态初始化块中。这样的事情:

An easy way to "solve" this would be to use a helper class (a la HibernateUtil) and to initialize the EntityManagerFactory in a static initialization block. Something like this:

public class JpaUtil {
    private static final EntityManagerFactory emf;

    static {
        try {
            factory = Persistence.createEntityManagerFactory("MyPu");
        } catch (Throwable ex) {
            logger.error("Initial SessionFactory creation failed", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

   ...

}

而且问题消失了。

这篇关于如何创建一个线程安全的EntityManagerFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 18:11