You seem to be using spring so your solution will be rather easy :
@Component
@Scope("prototype")
public class MyPersistenceContainer
{
@PersistenceContext
private EntityManager em;
public EntityManager getEntityManager()
{
return em;
}
}
And now you can simply inject an instance of this class in your constructor, it will always hold a valid EntityManager (because of the bean scope). Mind you : in a web environment you probably should use @SessionScope
or even @RequestScope
instead of prototype, this will save resources
But there is something to consider :
When using singleton-scoped beans that have dependencies on beans that
are scoped as prototypes, please be aware that dependencies are
resolved at instantiation time. This means that if you dependency
inject a prototype-scoped bean into a singleton-scoped bean, a brand
new prototype bean will be instantiated and then dependency injected
into the singleton bean... but that is all. That exact same prototype
instance will be the sole instance that is ever supplied to the
singleton-scoped bean, which is fine if that is what you want.
However, sometimes what you actually want is for the singleton-scoped
bean to be able to acquire a brand new instance of the
prototype-scoped bean again and again and again at runtime. In that
case it is no use just dependency injecting a prototype-scoped bean
into your singleton bean, because as explained above, that only
happens once when the Spring container is instantiating the singleton
bean and resolving and injecting its dependencies. If you are in the
scenario where you need to get a brand new instance of a (prototype)
bean again and again and again at runtime, you are referred to the
section entitled Section 4.3.7, “Method Injection”
So if you want to inject your "entity manager container-bean" into singleton beans (which is the default scope), have a look at https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-method-injection
Its rather important to set your scopes correctly, otherwise you might have (and will have) database inconsistencies, deadlocks or worse
@PersistenceContext
work for you? Injecting anEntityManager
via@Autowired
should work just as well – Covalence@PersistenceContext
? I can't find any documentation proving this. – Goosegog@Autowired
searches for any matching bean, meaning you might very well catch the container-managedEntityManager
. You can make sure to get your own if you specify a customEntityManagerFactory
– Archaeopteryx