我正在使用:
org.springframework.orm.hibernate4.HibernateTransactionManager的API是:
将指定工厂的Hibernate会话绑定到线程,可能允许每个工厂有一个线程绑定会话。
下面是我正在讨论的代码:
@Transactional
public void insertPerson(Person transientPerson) {
System.out.println("Current session in insert "+sessionFactory.getCurrentSession()); // Line 1
personDao.save(transientPerson);
executeConcurrently();
}
private void executeConcurrently() {
new Thread(new Runnable() {
@Transactional
public void run() {
System.out.println("This is a branew thread "+Thread.currentThread().getName());
System.out.println("In the new thread, session = "+sessionFactory.getCurrentSession()); // Line 2
}
}).start();
}在第1行中,我得到了会话,这是显而易见的。然而,第2行的执行显示了这个错误:
这是一个分支线程线程-2。
Exception in thread "Thread-2" org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
at edu.sprhib.service.impl.PersonServiceImpl$1.run(PersonServiceImpl.java:55)
at java.lang.Thread.run(Thread.java:724)我不明白的是,为何会出现这种情况呢?根据我的理解,Spring应该创建一个全新的会话,并将其与线程的ThreadLocal -2相关联。我的理解是错的还是密码?同时,我正在尝试调试Spring代码,而我的netbeans即使在将源代码附加到spring-orm jar之后也无法在其中进行调试(请注意,我不太擅长在框架代码中调试)。
任何帮助都将不胜感激。
提前谢谢你,穆斯塔法
发布于 2014-06-16 17:18:51
尝尝这个
@Transactional( propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertPerson(Person transientPerson) {
System.out.println("Current session in insert "+sessionFactory.getCurrentSession()); // Line 1
personDao.save(transientPerson);
executeConcurrently();
}
private void executeConcurrently() {
new Thread(new Runnable() {
@Transactional
public void run() {
System.out.println("This is a branew thread "+Thread.currentThread().getName());
System.out.println("In the new thread, session = "+sessionFactory.getCurrentSession()); // Line 2
}
}).start();
}通过使用Propagation.REQUIRED Spring容器处理会话,您不需要担心会话对象
如果您的会话对象被破坏,容器将创建新的会话,如果我们将我们的事务提到为propagation = Propagation.REQUIRED,则提供会话。
https://stackoverflow.com/questions/24248681
复制相似问题