从另一个方法调用的@Transactional方法不会获得一个事务 [英] @Transactional method called from another method doesn't obtain a transaction
问题描述
在Spring中,如果已经没有一个事务,那么用 @Transactional
注释的方法将获得一个新事务,但我注意到事务性方法没有获得任何事务,如果它是从非事务性的事务中调用的。这里是代码。
@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); //不起作用。
this.fooDao.save(bean); //作品
}
}
saveWrap( )
是一个常规方法,它调用事务性的 save()
,但是 saveWrap()
不会持续任何改变。
我正在使用Spring 3和Hibernate 3.我在这里做错了什么?谢谢。
这是Springs AOP的局限性之一。由于dao bean实际上是一个由Spring创建的代理,这意味着从同一个类中调用方法不会调用advice(这是事务)。其他切入点也是如此。
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()
is a regular method that calls save()
which is transactional, but saveWrap()
won't persist any changes.
I'm using Spring 3 and Hibernate 3. What am I doing wrong here? Thanks.
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屋!