从 sessionFactory.openSession() 休眠、监听或覆盖 opneSession

时间:2021-03-20 10:00:46

标签: hibernate transactions

问题是如果你使用

properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");

然后 Hibernate 将只对 sessionFactory.getCurrentSession() 进行 threadlocal 调用,而不是对 sessionFactory.openSession() 调用。

getCurrentSession 被委托给 CurrentSessionContext,但 openSession 没有,他们也没有注册。

如果有人也试图注册这些,这将是有问题的。我们想使用 ThreadLocal List,其中 getCurrentSession 将使用堆栈中的最后一个。

当前的实现似乎认为没有必要管理 openSession 调用,因为他们无法预见其他一些潜在用途(更正确的用途)。

那么,我是要覆盖实体 SessionFactoryImpl 类来挂钩,还是有一些事件被触发并且我可以在会话打开时挂钩

1 个答案:

答案 0 :(得分:1)

查看源代码,无法插入 InstanceType<T> 的行为。您可以将会话工厂包装在 openSession 中以减少样板。

SessionFactoryDelegatingImpl 挂钩要容易得多,您只需实现自定义 getCurrentSession