简体   繁体   中英

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:

  1. How can I access the session or session factory (without injecting it to the bean) (thus by thread locale)?

    2.How can I do the same in terms of JPA, thus using EnityManager / EntityManagerFactory?

  1. 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 the hibernate.cfg.xml . If it is set to thread , the returned session is get from the ThreadLocal , 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.

  2. AFAIK , there are no equivalent SessionFactory.getCurrentSession() in JPA . I think you have manually set and get the EntityManager to the ThreadLocal


Reference

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM