Is it necessary to call a flush() (JPA interface) in this situation?

有些话、适合烂在心里 提交于 2019-11-30 02:48:50

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/949427/is-it-necessary-to-call-a-flush-jpa-interface-in-this-situation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!