簡體   English   中英

在存儲庫中沖洗

[英]Flushing in the repositories

在我看到的大多數代碼中(春季),似乎沒有人從存儲庫中調用entityManager.flush() 有什么理由嗎?

是的,這是有原因的。 默認情況下,在提交事務之前或在執行查詢之前,將自動調用flush() ,其結果可能取決於尚未刷新的修改。 因此,幾乎不需要顯式的flush()

盡可能晚刷新是一件好事,因為這樣可以避免在事務回滾時避免執行查詢。

通常,如果您的JPA代碼正確地包含在事務中,則刷新將自動完成。 如果您在執行代碼期間查看日志,則可以看到:

  • 直到:更新或創建操作才寫入數據庫
    • 會話結束(因此交易結束); 因此批處理SQL命令
    • 執行“查找”操作(因為必須對數據庫的一致數據集執行此操作)
  • SQL命令可以重新排序以提高效率

因此,如果要顯式的 “刷新”,則flush命令很有用。

Animal animal = new Animal();
animal.setName(“Pluto”);
entityManager.persist(animal); /* pluto is saved here */

Owner owner = new Owner();
owner.setName(“Mickey”);
animal.setOwner(owner);
entityManager.persist(owner); /* mickey is saved here */

owner.setName(“Minnie”);
entityManager.merge(owner);
animal.setName(“Mickey”);
entityManager.merge(animal);

/* pluto and mickey are updated here, just before the find query */
Query q = entityManager.createQuery(“FROM Animal a”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM