In my case of application managed transaction, I've to choose between:
EntityManager
and calling clear()
before each new transaction. Share the EntityManager
using a ThreadLocal
.EntityManager
for each transaction.I don't have much experience on JPA. My question is which one is better in terms of performance?
The link provided by okwap is very helpfull. To make sure it will not slip through, and to follow the board rules, I put a copy here:
- an EntityManager contains a persistence context, that will track everything read through it, so to avoid bloated memory, you should acquire a new one, or clear it at some point - if you read the same object through two different EntityManager you will get different objects back, so will loose object identity, which is something to consider
Based on that, I will add, that reading through two different EntityManager may even give objects with different content, if a database transaction was performed by someone else in the meantime. But if reading repeatedly through the same entitymanager, the 2nd read wil just get the objet from the entitymanager cache, so the newer state wil just not be visible.
I would recommend creating a new EntityManager per transaction. This is the way JPA was designed. The EntityManager should not be an expensive object to create. (the EntityManagerFactory is very expensive though, so ensure you only have one of those).
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