java 在这种情况下是否需要调用flush()(JPA接口)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/949427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it necessary to call a flush() (JPA interface) in this situation?
提问by Kewei Shang
Because calling a flush() to get every entities persist from memory to database. So if I use call too much unnecessary flush(), it could take much time therefore not a good choice for the performance. Here is a scenario that I don't know when to call a flush()?
因为调用 flush() 来让每个实体从内存持久化到数据库。因此,如果我调用过多不必要的flush(),可能会花费很多时间,因此对于性能而言不是一个好的选择。这是一个我不知道什么时候调用flush()的场景?
//Order and Item have Bidirectional Relationships
Order ord = New ord("my first order");
Item item = New Item("tv",10);
//...process item and ord object
em.persist(ord);//em is an instance of EntityManager
em.flush();// No.1 flush()
item.setOrder(ord);
em.persist(item);
Set<Item> items= new HashSet<Item>();
items.add(item);
ord.setItems(items);
em.flush();// No.2 flush()
My question is: calling of the No.1 flush could be avoid or not?
我的问题是:是否可以避免跟注 1 号同花?
The things I worried is: in order to do the item.setOrder(ord), we need an database id of ord. And calling only em.persist(ord)cannot generate an database id, so I have to call the em.flush()before item.setOrder(ord). So what's your opinion guys?
我担心的是:为了执行item.setOrder(ord),我们需要一个 ord 的数据库 ID。并且只调用em.persist(ord)不能生成数据库 id,所以我必须在item.setOrder(ord)之前调用em.flush( )。那么小伙伴们有什么看法呢?
Thanks in advance.
提前致谢。
采纳答案by Salandur
i should first construct the structure, and after that persist everything.
我应该首先构建结构,然后坚持一切。
Order ord = New ord("my first order");
Item item = New Item("tv",10);
item.setOrder(ord);
Set<Item> items= new HashSet<Item>();
items.add(item);
ord.setItems(items);
em.persist(ord);
In this way, you persist the whole tree in one call and is flush not needed.
通过这种方式,您可以在一次调用中保留整个树,并且不需要刷新。
In good object design, you should use the way duffymo described to wire your objects.
在好的对象设计中,你应该使用 duffymo 描述的方式来连接你的对象。
回答by duffymo
I think you should be doing all this in a transactional context and let it handle these issues for you.
我认为您应该在事务上下文中完成所有这些工作,并让它为您处理这些问题。
You need to embed the bidirectional relationship in the objects:
您需要在对象中嵌入双向关系:
class Parent
{
private List<Child> children;
public boolean addChild(Child c)
{
c.setParent(this); // this is the key piece
return this.children.add(c);
}
}
class Child
{
private Parent parent;
public void setParent(Parent p)
{
this.parent = p;
}
}

