我目前正在重新学习 Hibernate,我已经有五六年没有使用它了,并且我正在尝试回想我们在旧工作场所中使用它的方式(Hibernate in Action 是按订单...)
我目前没有在我的应用程序中使用 spring,我想知道的一件事是如何最好地检索我的应用程序中的 SessionFactory 以在我的持久性助手之间共享它 - 我似乎记得您通常只想要使用一个。在我当前的代码库中,我选择在所有持久性“助手”通用的类中这样做:
public abstract class AbstractHelper {
private static final String CONFIG = "configuration.xml";
private static SessionFactory sessionFactory = null;
/**
* @return SessionFactory the Hibernate SessionFactory.
*/
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure(CONFIG);
ServiceRegistryBuilder serviceRegistryBuilder =
new ServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(
serviceRegistryBuilder.buildServiceRegistry());
}
return sessionFactory;
}
}
这对人们来说是否有意义,或者出于性能等原因我应该以不同的方式来解决这个问题?
最佳答案
当从多个线程访问代码时,您可能会遇到麻烦。当两个线程访问 getSessionFactory()
时,一个线程可能会创建一个 SessionFactory
,另一个线程可能会在第一个线程之前到达 if(sessionFactory == null)
被分配给变量。
解决此问题的最简单方法是使 getSessionFactory()
synchronized
。这可能会导致一些锁定开销并对性能产生影响。
有关更复杂的方法,请参阅例如 here或者在“Singleton pattern java”上进行一些谷歌搜索。
关于java - 在没有Spring的情况下使用SessionFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753911/