[英]Data not saved in db when the time @PostPersist got called
在數據庫中創建對象后,我需要向其他微服務發送請求。 我只發送對象 id,所以其他微服務需要再次調用 db 以獲取包含大量其他內容的信息。
但是,當其他微服務嘗試使用接收到的 id 查找記錄時,它無法在數據庫中找到保存的記錄。
我試過調試,即使@postPersist 被調用,記錄似乎也不會持續。 它將在@PostPersist 執行后保存。
有沒有人可以為此提供解決方法。 我真的需要再次查詢數據庫,因為這是一個自定義要求。 我使用mysql和spring boot
public class EmployeeListener {
@PostPersist
public void sendData(Employee employee){
Long id = employee.getEmployeeId();
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange("http://localhost:8081/service/employee"+id, HttpMethod.POST, null, String.class);
}
}
@Entity
@EntityListeners(EmployeeListener.class)
public class Employee {
//
}
問題是 JPA 生命周期事件發生在與您的保存操作相同的事務中,但是查找,因為它發生在不同的服務器上,所以只能在您的事務關閉后發生。
因此,我推薦以下設置:在Collection
收集需要通知的 id,然后在交易完成時發送數據。
如果您想在一種方法中進行發送操作和保存操作, [TransactionTemplate][1]
可能比通過注釋進行事務管理更好用。
您也可以考慮域事件。 請注意,它們僅在實際調用save
時觸發。 這些事件的好處是它們使用ApplicationEventPublisher
發布,其偵聽器是 Spring Bean,因此您可以注入任何您認為有用的 bean。 他們仍然需要一種方法來打破如上所述的交易
@PostPersist
注釋方法在同一個事務中被調用,默認的 flash 模式是 AUTO,這就是為什么你在數據庫中看不到記錄的原因。 您需要強制刷新:
@Component
public class EmployeeListener {
@PersistenceContext
private EntityManager entityManager;
@PostPersist
public void sendData(Employee employee){
// Send it to database
entityManager.flush();
Long id = employee.getEmployeeId();
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange("http://localhost:8081/service/employee"+id, HttpMethod.POST, null, String.class);
}
}
請注意, EmployeeListener
需要是 Spring 管理的 bean。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.