IBM suggests that the best practice for using EntityManagers is get/use/close. If EntityManager is not closed, there's a chance that the same EntityManager may be used by more than one thread which will result in the following error:
<openjpa-2.1.2-SNAPSHOT-r422266:1179900 fatal general error> org.apache.openjpa.persistence.PersistenceException: Multiple concurrent threads attempted to access a single broker. By default brokers are not thread safe; if you require and/or intend a broker to be accessed by more than one thread, set the openjpa.Multithreaded property to true to override the default behavior.
If you load an object which has OneToMany collection mapped as fetch=LAZY like this:
public T find(Object id) {
T t = null;
EntityManager em = getEm();
t = em.find(type, id);
em.close();
return t;
}
EntityManager getEm() {
if(this.em ==null || !this.em.isOpen()) {
this.em = emf.createEntityManager();
}
return this.em;
}
The collection will always be null as by the time someone calls the getter, EntityManager is closed. The collection is only loaded if fetch is EAGER but that results in a SQL join every single time which is slow.
So it's either "Multiple threads" error, or openjpa.Multithreaded=true which is a bad practice or it's slow because of the SQL join every single time even if the collection is not needed. Is there any way to do it properly so it's both fast with Lazy fetch and done using best practices only?