简体   繁体   English

在存储库中冲洗

[英]Flushing in the repositories

In most of the code I see (Spring), it seems no one calls entityManager.flush() from a repository. 在我看到的大多数代码中(春季),似乎没有人从存储库中调用entityManager.flush() Is there a reason for that ? 有什么理由吗?

Yes, there is a reason. 是的,这是有原因的。 By default, flush() is called automatically before the transaction is committed, or before executing a query whose result might depend on the not-flushed-yet modifications. 默认情况下,在提交事务之前或在执行查询之前,将自动调用flush() ,其结果可能取决于尚未刷新的修改。 So an explicit flush() is almost never needed. 因此,几乎不需要显式的flush()

And it's a good thing to flush as late as possible, because it avoids executing queries in case the transaction is rolled back. 尽可能晚刷新是一件好事,因为这样可以避免在事务回滚时避免执行查询。

Usually, if your JPA code is correctly enclosed in a transaction, flush is done automatically. 通常,如果您的JPA代码正确地包含在事务中,则刷新将自动完成。 If you keep a look at logs during code execution you can see: 如果您在执行代码期间查看日志,则可以看到:

  • update or create operation are not write to the database until: 直到:更新或创建操作才写入数据库
    • the end of the session (thus end of transaction); 会话结束(因此交易结束); thus batching the SQL commands 因此批处理SQL命令
    • a 'find' operation is executed (because it must be done on a coherent data set by the DB) 执行“查找”操作(因为必须对数据库的一致数据集执行此操作)
  • SQL commands can be reorder to be more efficient SQL命令可以重新排序以提高效率

Thus, flush command is useful if you want explicit 'flush'. 因此,如果要显式的 “刷新”,则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