How to get Session or EntityManager bound to thread?
As I understand when I use hibernate with Spring transactions, a session is bound to thread using ThreadLocal. My questions are:
How can I access the session or session factory (without injecting it to the bean) (thus by thread locale)?
2.How 开发者_StackOverflow中文版can I do the same in terms of JPA, thus using EnityManager / EntityManagerFactory?
You should use the SessionFactory.getCurrentSession() to get your Session. What the session returned from this method depends on the configuration parameter
hibernate.current_session_context_class
in thehibernate.cfg.xml
. If it is set tothread
, the returned session is get from theThreadLocal
, which means that if it is called for the first time in the current Java thread, a new Session is opened and returned . If it is called again in the same thread , the same session will be returned.AFAIK , there are no equivalent
SessionFactory.getCurrentSession()
in JPA . I think you have manually set and get theEntityManager
to theThreadLocal
Reference
- Hibernate Contextual sessions
- Sessions and transactions
I was trying to figure this out today and ended up doing it this way:
@PersistenceContext(unitName = "jpaSessionFactoryName")
private EntityManager jpaSession;
I found this documentation very helpful: https://docs.spring.io/spring/docs/4.3.2.RELEASE/spring-framework-reference/htmlsingle/#orm-jpa-straight
When you use @PersistenceContext, Spring injects a proxy that gives you an EntityManager bound to the current transaction (or a new one, if there is not any). This looks like a direct substitute for hibernate's:
sessionFactory.getCurrentSession();
which is exactly what I was looking for.
精彩评论