首页 > 解决方案 > Spring @Transactional 行为

问题描述

当我创建一个带有两个实体的方法@Transactional 时,一个用于更新,一个用于插入,Spring 不使用相同的事务进行更新和插入是正常的吗?

@Transactional
public void myMethod(args...){
    Entity1 entity1 = entity1Repository.findById(args);
    entity1.setValue(args);
    Entity2 entity2 = new Entity2();
    entity2.setValue(args);
    entity2Respository.save(entity2);
}

在休眠日志中,我看到两个事务,一个用于 findBy 和 update,另一个用于插入。

标签: javaspringdatabasehibernatetransactions

解决方案


你从哪里调用 myMethod() ?如果它来自同一个类,那么@Transactional注释甚至不存在,因为没有在 spring 代理对象上调用方法,并且您将有单独的事务用于更新和插入。


推荐阅读