我使用的是jpa实体listner类where和spring数据存储库。在@PreMethod更新中,如果我使用@Transactional(propagation = Propagation.REQUIRES_NEW)
,我将直接从数据库中获取数据。如果我在called inside @PreMethod
的私有方法(getOldEmployee(上使用相同的事务注释,我不会从数据库中获取数据,而是使用相同的最新会话数据,不确定发生这种行为的原因
实体类
@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
}
}
Spring仅在public方法上应用Transactional设置,在其他情况下会忽略这些设置
来自Spring文档:
使用代理时,应应用@Transactional注释仅适用于具有公共可见性的方法。
它只适用于外部调用的方法,即事务方法应该存在于另一个类中,并且应该从该类调用。
这意味着事务方法也必须是公共的,因为如果另一个类的方法不是公共的,我们就不能调用该方法。
因此,如果直接调用同一类的本地方法,Spring将无法实现事务功能所需的代理魔术。