从另一个方法调用的@Transactional 方法不获取事务 [英] @Transactional method called from another method doesn't obtain a transaction

查看:60
本文介绍了从另一个方法调用的@Transactional 方法不获取事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Spring 中,一个用 @Transactional 注释的方法会在没有新事务的情况下获得一个新事务,但我注意到事务方法如果被调用则不会获得任何事务从一个非事务性的.这是代码.

In Spring, a method that is annotated with @Transactional will obtain a new transaction if there isn't one already, but I noticed that a transactional method does not obtain any transaction if it is called from a non-transactional one. Here's the code.

@Component
public class FooDao {
    private EntityManager entityManager;

    @PersistenceContext
    protected void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Transactional
    public Object save(Object bean) {
        return this.entityManager.merge(bean);
    }

    public Object saveWrap(Object bean) {
        return save(bean);
    }
}

@Component
public class FooService {
    private FooDao fooDao;

    public void save(Object bean) {
        this.fooDao.saveWrap(bean); // doesn't work.
        this.fooDao.save(bean); // works
    }
}

saveWrap() 是调用 save() 的常规方法,这是事务性的,但 saveWrap() 不会保留任何更改.

saveWrap() is a regular method that calls save() which is transactional, but saveWrap() won't persist any changes.

我使用的是 Spring 3 和 Hibernate 3.我在这里做错了什么?谢谢.

I'm using Spring 3 and Hibernate 3. What am I doing wrong here? Thanks.

推荐答案

这是 Springs AOP 的局限性之一.因为dao bean在spring创建的时候其实就是一个proxy,也就是说从同一个类内部调用一个方法不会调用advice(也就是事务).任何其他切入点也是如此

It is one of the limitations of Springs AOP. Because the dao bean is in fact a proxy when it is created by spring, it means that calling a method from within the same class will not call the advice (which is the transaction). The same goes for any other pointcut

这篇关于从另一个方法调用的@Transactional 方法不获取事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆