JPA desktop application single or multiple instances of EntityManager
Asked Answered
P

2

6

In a desktop application that runs in a Java SE environment (no DI, no frameworks other than JPA, plain Java) it is better to create a new EntityManager for each operation in the persistence layer or share a single instance of the EntityManager in the entire persistence layer?

Pro/Cons for both the solutions?

Update:

The application uses one DB instance with only one schema.

Parsons answered 18/5, 2014 at 8:21 Comment(0)
D
5

There are at least three good reasons to have one EM per operation.

If any other process modifies the database (or even if the same process uses JDBC or batch queries to modify the database), the EM will have stale data in its cache. If your EM only lives for the duration of a transaction, you have almost no risk of having to deal with stale data.

If any exception occurs with the EM, then its state is not reliable anymore, and the EM must be closed.

If several threads access the EntityManager, you need one EM per thread because the EM is not thread-safe.

And here's a fourth one: even assuming that everything goes fine always, that only one thread accesses the database, the cache of the EM will grow up an up and will consume memory. You also risk in having an inconsistent object graph in the cache because you forgot to initialize the inverse side of an association. Having one EM per transaction doesn't have this problem.

Description answered 18/5, 2014 at 9:26 Comment(0)
L
1

EntityManager is an entry point to JPA world. It provides API to access the JPA session and manages the schema. It also holds cache.

So, IMHO there is no reason to hold EntityManager per operation. There can be reason to hold EntityManager per DB schema. If for example your application works with 2 absolutely different DB schemas that do not have any shared table you can use EntityManager per schema.

Labuan answered 18/5, 2014 at 8:32 Comment(2)
The EntityManager doesn't manage the schema. The EntityManagerFactory does that. And there are at least three good reasons to have one EM per operation: if any other process modifies the database (or even if the same process uses JDBC or batch queries to modify the database), the EM will have stale data in its cache. If any exception occurs with the EM, then its state is not reliable anymore. If several threads access the EntityManager, you need one EM per thread because the EM is not thread-safe.Description
Good point, @JB Nizet. Why don't you post your comment as an alternative answer?Labuan

© 2022 - 2024 — McMap. All rights reserved.