Spring Data Jpa transaction(propagation = Propagation.REQUIRES_NEW)未在私有方法中打开新事务,获取作为参数传递的相同值

nxowjjhe  于 8个月前  发布在  Spring
关注(0)|答案(2)|浏览(75)

我使用的是jpa实体listner类where和spring数据仓库。在@PreMethod更新中,如果我使用@Transactional(propagation = Propagation.REQUIRES_NEW),我将直接从数据库获取数据。如果我在私有方法(getOldEmployee)上使用相同的transactional annotation,即called inside @PreMethod,我不会从数据库获取数据,而是使用相同的最新会话数据,不知道为什么会发生这种行为

实体类

@Entity
@Table(name = "Employee")
@EntityListeners({EmployeeListener.class)
public class Employee extends AuditEntity implements Serializable {

}

高级课程

@Component
 public class EmployeeListner{
 
 @Autowired
 EmployeeRepository employeeRepository;

  @PreUpdate
  @Transactional(propagation = Propagation.REQUIRES_NEW)   //if use here I get the employee database value before updating the database
  public void preUpdateEvent(Employee employee) {
    Employee employee=getOldEmployee(employee);
  }

  private Employee getOldEmployee(Employee employee) {     //if inspite of using  @Transactional(propagation = Propagation.REQUIRES_NEW) in @PreMethod if use here I am not getting the database value rather getting latest value
    Optional<Employee> getOldEmployeeOptional =employeeRepository.findById(employee.getId());
    getOldEmployeeOptional  
  }
}
hts6caw3

hts6caw31#

Spring只在public方法上应用transmitting设置,在其他情况下,设置被忽略。
Spring文档:
当使用代理时,你应该只对具有公共可见性的方法应用@ transmitting注解。

nbewdwxp

nbewdwxp2#

它只适用于外部调用的方法,即transaction方法应该存在于另一个类中,并且应该从这个类调用。
这意味着transaction方法也必须是public的,因为如果另一个类的方法不是public的,我们就不能调用它。
因此,如果您直接调用同一个类的本地方法,Spring将无法执行Transaction功能所需的代理魔术。

相关问题