[英]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:
如果您在执行代码期间查看日志,则可以看到:
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.