开发者

How to get Session or EntityManager bound to thread?

开发者 https://www.devze.com 2023-03-31 03:48 出处:网络
As I understand when I use hibernate with Spring transactions, a session is bound to thread using ThreadLocal. My questions are:

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 开发者_StackOverflow中文版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

  • 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消