Using JPA to persist(store) Java entity in the database

1. Batch Store

Storing a large number of entity objects requires special consideration.The combination of the clear and flush methods can be used to save memory in large transactions: 

 1  em.getTransaction().begin();
 2   for (int i = 1; i <= 1000000; i++) {
 3       Point point = new Point(i, i);
 4       em.persist(point);
 5       if ((i % 10000) == 0) {
 6           em.flush();
 7           em.clear();
 8       }
 9   }
10   em.getTransaction().commit();
View Code

Managed entity objects consume more memory than ordinary non managed Java objects.Therefore,holding 1,000,000 managed Point instances in the persistence context might consume too much memory.The sample code above clears the persistence context after every 10,000 persist.Updates are flushed to the database before clearing,otherwise they would be lost.

Updates that are sent to the database using flush are considered temporary and are only visible to the owner EntityManager until a commit.With no explicit commit,these updates are later discarded.The combination of clear and flush enables moving the temporary updates form memory to the database.

Note: Flushing updates to the database is sometimes also useful before executing queries in order to get up to date results.

Storing large amount of entity objects can also be performed by multiple transactions:

 1  em.getTransaction().begin();
 2   for (int i = 1; i <= 1000000; i++) {
 3       Point point = new Point(i, i);
 4       em.persist(point);
 5       if ((i % 10000) == 0) {
 6           em.getTransaction().commit();
 7           em.clear();          
 8           em.getTransaction().begin();
 9       }
10   }
11   em.getTransaction().commit();
View Code

Splitting a batch store into multiple transactions is more efficient than using one transaction with multiple invocations of the flush and clear methods. So using multiple transactions is preferred when applicable.

posted @ 2016-04-29 14:39  Jacky312  阅读(166)  评论(0编辑  收藏  举报