@Transactional不执行提交

时间:2012-10-16 18:55:43

标签: mysql spring jpa transactions

请参阅我的以下代码段。

@Transactional
public void saveMembersService(List<Member> list1, List<Member> list2)
{
    saveMembersDAO(list1); // does not perform commit. Why?
    saveMembersDAO(list2); // does not perform commit. Why?
} // does perform commit only here!

@PersistenceContext
private EntityManager em;

@Transactional
public void saveMembersDAO(List<Member> members)
    throws HibernateException
{
    Iterator<Member> it = members.iterator();
    while (it.hasNext())
    {
        Member wsBean = it.next();
        em.persist(wsBean); // overall commit will be made after method exit
    }
}

我使用MySQL作为DB。我在上面的方法执行后观察MySql日志。但是在 saveMembersService 方法执行后,我只能看到单个提交。我希望每个事务方法调用都能看到两个提交。我哪里错了?

更新1:抱歉,我忘记将@Transactional添加到我的服务方法中。现在修好了

更新2 :我已使用 Propagation.REQUIRES_NEW 属性检查了DAO - 结果是相同的(在服务方法中使用和不使用@Transactional)

1 个答案:

答案 0 :(得分:3)

当使用@Transactional时,Spring会在您的类周围创建一个代理,并且内部调用的方法不会在代理中传递。

你必须这样做。您可以通过在Spring上下文中创建TransactionTemplate来清理它。

@Autowired
private PlatformTransactionManager transactionManager;

public void saveMembersDAO(List<Member> members)
    throws HibernateException
{
    TransactionDefinition txDef = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager, trDef)

    txTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Iterator<Member> it = members.iterator();
            while (it.hasNext())
            {
                Member wsBean = it.next();
                em.persist(wsBean);
            }
        }
    });
}

如果您使用的是AspectJ,并且您希望进行2次提交。您必须在saveMembersDAO上使用@Transactional(propagation = Propagation.REQUIRES_NEW)