在这种情况下是否需要调用flush()(JPA接口)? [英] Is it necessary to call a flush() (JPA interface) in this situation?

查看:111
本文介绍了在这种情况下是否需要调用flush()(JPA接口)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为调用flush()来获取每个实体从内存到数据库的持久性。因此,如果我使用调用太多不必要的flush(),可能需要很长时间,因此不是性能的好选择。这是一个我不知道什么时候调用flush()的场景?

  // Order和Item有双向关系
订单ord =新订单(我的第一个订单);
Item item = New Item(tv,10);

//...process项目和ord对象

em.persist(ord); // em是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()

我的问题是:呼叫第一次冲洗可以避免或不是?



我担心的是:为了做 item.setOrder(ord),我们需要一个ord的数据库id。并且只调用em.persist(ord)不能生成数据库ID,所以我必须在 item.setOrder(ord)之前调用em.flush() 。所以,你们有什么看法的人?



在此先感谢。



  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);

通过这种方式,您可以在一次调用中坚持整个树并且不需要flush。



在良好的对象设计中,您应该使用duffymo描述的方式来连接对象。


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()?

//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?

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?

Thanks in advance.

解决方案

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.

这篇关于在这种情况下是否需要调用flush()(JPA接口)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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