我们找到了两种解决方法。
其中之一是在 SessionFactory 上用我们的 Class 定义 hibernate.current_session_context_class。我们的类设置了 JTASessionContext 的实现。
<property name="hibernateProperties">
<props>
*
<prop key="hibernate.current_session_context_class">org.path.to.my.context.MySpringSessionContext</prop>
*
</props>
</property>
自己的会话上下文:
public class MySpringSessionContext extends SpringSessionContext {
public MySpringSessionContext(SessionFactoryImplementor sessionFactory) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
super(sessionFactory);
Field transactionManager = this.getClass().getSuperclass().getDeclaredField("transactionManager");
transactionManager.setAccessible(true);
Object value = transactionManager.get(this);
if (value != null) {
Field jtaSessionContext = this.getClass().getSuperclass().getDeclaredField("jtaSessionContext");
jtaSessionContext.setAccessible(true);
jtaSessionContext.set(this, new MySpringJtaSessionContext(sessionFactory));
}
}
}
自己的 JTASessionContext:
public class MySpringJtaSessionContext extends SpringJtaSessionContext {
private BeanFactory beanFactory;
private String entityInterceptor;
public MySpringJtaSessionContext(SessionFactoryImplementor factory) {
super(factory);
//Ugly but we need Spring
Interceptor interceptor = factory.getInterceptor();
if(interceptor instanceof MyBeanFactoryInterceptor){
this.beanFactory = ((MyBeanFactoryInterceptor) interceptor).getBeanFactory();
this.entityInterceptor = ((MyBeanFactoryInterceptor) interceptor).getEntityInterceptorBeanName();
}
}
@Override
protected SessionBuilder baseSessionBuilder() {
return super.baseSessionBuilder().interceptor(getEntityInterceptor());
}
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
if (this.beanFactory == null) {
return EmptyInterceptor.INSTANCE;
}
return this.beanFactory.getBean((String) this.entityInterceptor, Interceptor.class);
}
}
另一种解决方法:使用OpenSessionInterceptor(覆盖),但还有一些其他困难。(刷新,关闭会话)但是像:
使用实体拦截器打开会话:
@Override
protected Session openSession() {
try {
Session session = getSessionFactory().withOptions().interceptor(getEntityInterceptor()).openSession();
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
session.setFlushMode(FlushMode.MANUAL);
} else {
session.setFlushMode(FlushMode.AUTO);
}
return session;
} catch (HibernateException ex) {
throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
}
}
从 Spring 获取拦截器:
public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException {
if (this.entityInterceptor instanceof String) {
if (this.beanFactory == null) {
throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set");
}
return this.beanFactory.getBean((String) this.entityInterceptor, Interceptor.class);
}
return (Interceptor) this.entityInterceptor;
}