首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@Transactional ()不工作

@Transactional ()不工作
EN

Stack Overflow用户
提问于 2014-06-16 17:00:46
回答 1查看 1.1K关注 0票数 0

我正在使用:

org.springframework.orm.hibernate4.HibernateTransactionManager的API是:

将指定工厂的Hibernate会话绑定到线程,可能允许每个工厂有一个线程绑定会话。

下面是我正在讨论的代码:

代码语言:javascript
复制
@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。

代码语言:javascript
复制
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之后也无法在其中进行调试(请注意,我不太擅长在框架代码中调试)。

任何帮助都将不胜感激。

提前谢谢你,穆斯塔法

EN

回答 1

Stack Overflow用户

发布于 2014-06-16 17:18:51

尝尝这个

代码语言:javascript
复制
@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,则提供会话。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24248681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档