Come posso ottenere l'oggetto di sessione se ho l'EntityManager
-
30-09-2019 - |
Domanda
ho
private EntityManager em;
public List getAll(DetachedCriteria detachedCriteria) {
return detachedCriteria.getExecutableCriteria( ??? ).list();
}
Come posso recuperare la sessione se sto usando EntityManager o come posso ottenere il risultato dal mio DetachedCriteria?
Soluzione
Per essere completamente esaustivo, le cose sono diverse, se si sta utilizzando un JPA 1.0 o un'implementazione JPA 2.0.
JPA 1.0
Con JPA 1.0, dovreste usare EntityManager#getDelegate()
. Ma tenete a mente che il risultato di questo metodo è la realizzazione specifica vale a dire non portatile dal server di applicazioni utilizzando Hibernate all'altro. Ad esempio con JBoss si dovrebbe fare:
org.hibernate.Session session = (Session) manager.getDelegate();
con GlassFish , dovreste fare:
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
Sono d'accordo, che è orribile, e la specifica è la colpa qui (non abbastanza chiaro).
JPA 2.0
Con JPA 2.0, c'è un nuovo (e molto meglio) EntityManager#unwrap(Class<T>)
metodo che è da preferire EntityManager#getDelegate()
per nuove applicazioni.
Quindi, con Hibernate come JPA 2.0 implementazione (vedi 3.15 Native Hibernate API ), si farebbe:.
Session session = entityManager.unwrap(Session.class);
Altri suggerimenti
Si veda la sezione " 5.1. Accesso Hibernate API da JPA " nella Hibernate ORM Manuale dell'utente :
Session session = entityManager.unwrap(Session.class);
In questo modo spiegare meglio.
EntityManager em = new JPAUtil().getEntityManager();
Session session = em.unwrap(Session.class);
Criteria c = session.createCriteria(Name.class);
ho lavorato in wildfly ma stavo usando
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
ed il corretto stato
org.hibernate.Session session = (Session) manager.getDelegate();