休眠:我需要flush()吗? [英] Hibernate: Do I ever need to flush()?

查看:119
本文介绍了休眠:我需要flush()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有双向的一对多关系。我试图坚持它在这个文件中:



http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-parentchild.html#example-parentchild-bidir

  Parent p =(Parent)session.load(Parent.class,pid); 
Child c = new Child();
c.setParent(p);
p.getChildren()。add(c);
session.save(c);
session.flush();

是否需要 flush()?它究竟做了什么?我知道它做了什么,但是我发现它花了我100毫秒,如果可能,我真的很想避免它。

session.load ()甚至 session.refresh()被调用,并且我没有刷新,它是否会包含新的 Child 在集合中?

解决方案

调用flush将会话状态与数据库同步。你不需要在那个时候显式刷新。 Hibernate足够聪明,知道何时需要用会话更新数据库,例如在执行查询之前。



在某些时候,100ms的成本必须发生,因为在应用程序中使用数据库是不可避免的结果。 Hibernate能够延迟这个操作并且批量修改数据库以减少往返数据库的次数。



当事务结束时(默认),Hibernate将刷新会话如果您在同一会话中调用加载,则会从该会话返回相同的对象。如果您在新会话中调用加载,Hibernate将刷新所做的更改,并且您的孩子将进入该集合。



如果您要清除会话或从在执行刷新之前的会话时,您会发现您的孩子不在场。



文档中的这一章应该有所帮助。


I have a bidirectional one-to-many relationship. I'm trying to persist it like in this doc:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-parentchild.html#example-parentchild-bidir

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();

Is the flush() required there? What exactly does it do? I know what it does, but I discovered it costs me 100 ms and I would really like to avoid it if possible.

When session.load() or even session.refresh() is called and I hadn't flushed, will it include the new Child in the collection?

解决方案

The call to flush will synchronise the session state with the database. You do not need to explicitly flush at that point. Hibernate is clever enough to know when it needs to update the database with the session e.g. before executing a query.

That 100ms cost will have to be incurred at some point since it's an inevitable consequence of using a database in your application. Hibernate is able to delay this operation and batch up database changes to minimise round trips to the database.

Hibernate will flush the session when the transaction ends (by default) and so if you call load in the same session you will get the same object back from the session. If you call load in a new session Hibernate will have flushed the changes and your child will be in the collection.

If you were to clear the session or evict your object from the session before a flush was performed you would find that your child is not present.

This chapter from the docs should help.

这篇关于休眠:我需要flush()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆