@PostConstruct
从一些对先前问题的搜索中,我发现我不能指望以一种带有注释的方法提供Hibernate会话像这样:
getSession().getSessionFactory().openSession()
这对我来说就像一种魅力,但感觉有点……不对劲……有什么我应该注意的潜在陷阱吗?
Session
Spring为每个线程管理 Hibernate的边界。
我不能指望在使用 @PostConstruct 注释的方法中可以使用 Hibernate 会话
那是错误的,你可以在那个时候有一个会话。
您可以通过多种方式做到这一点,一种是定义 Session 的 bean,并告诉 Spring 通过 SessionFactory bean 的工厂方法“openSession”实例化它。像这样的东西:
<!-- Prototype so there is a new Session in every injection -->
<bean id="newSession" scope="prototype" class="...Session" factory-bean="sessionFactory"
factory-method="openSession" ... >
</bean>
此外,您可能想通过 Spring SessionFactory 实现告诉 Spring 使用 Hibernate 托管会话。