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.
JPA also defines a COMMIT flush mode, which is described as follows: If FlushModeType. COMMIT is set, the effect of updates made to entities in the persistence context upon queries is unspecified. When executing a JPQL query, the persistence context is only flushed when the current running transaction is committed.
flush() does is to empty the internal SQL instructions cache, and execute it immediately to the database.
You can do that selectively with EntityManager. detach() , or en masse with EntityManager. clear() .
The solution is to use @javax. persistence. Version on a new versionNumber column in all the tables. If you have a parent and child table then use @Version column in all the entity classes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With