Java 如何在 Tomcat 6 中为 Hibernate 使用 JTA 支持?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2552612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use JTA support in Tomcat 6 for Hibernate?
提问by EugeneP
They recommend using JTA transaction support in Java EE environment.
他们建议在 Java EE 环境中使用 JTA 事务支持。
But how to configure JTA in Tomcat6 so that Hibernate Session could use it ?
但是如何在 Tomcat6 中配置 JTA 以便 Hibernate Session 可以使用它?
Starting with version 3.0.1, Hibernate added the
SessionFactory.getCurrentSession()
method. Initially, this assumed usage of JTA transactions, where the JTA transaction defined both the scope and context of a current session. Given the maturity of the numerous stand-alone JTA TransactionManager implementations, most, if not all, applications should be using JTA transaction management, whether or not they are deployed into a J2EE container. Based on that, the JTA-based contextual sessions are all you need to use.
从 3.0.1 版本开始,Hibernate 添加了该
SessionFactory.getCurrentSession()
方法。最初,这假定使用 JTA 事务,其中 JTA 事务定义了当前会话的范围和上下文。鉴于众多独立 JTA TransactionManager 实现的成熟度,大多数(如果不是全部)应用程序都应该使用 JTA 事务管理,无论它们是否部署到 J2EE 容器中。基于此,您只需要使用基于 JTA 的上下文会话。
(Hibernate Reference Documentation | Architecture. Contextual Sessions)
采纳答案by Pascal Thivent
If you want JTA support in Tomcat you'll need to use a standalone transaction manager like Atomikos, JOTM, Bitronix, SimpleJTA, JBossTSor GeronimoTM/Jencks. But honestly, if you're not going to handle transactions across multiple resources, then you can live without JTA (and if you really need JTA, use a full blown application server).
如果您想在 Tomcat 中获得 JTA 支持,您需要使用一个独立的事务管理器,如Atomikos、JOTM、Bitronix、SimpleJTA、JBossTS或GeronimoTM/Jencks。但老实说,如果您不打算跨多个资源处理事务,那么您可以不用 JTA(如果您真的需要 JTA,请使用成熟的应用程序服务器)。
回答by FRotthowe
If you just want to use SessionFactory.getCurrentSession()
you can just add the following two lines to your hibernate.cfg.xml:
如果您只是想使用,SessionFactory.getCurrentSession()
您可以将以下两行添加到您的 hibernate.cfg.xml 中:
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
This will give you a unique Session for each thread. As a servlet request is always handled within one thread (given that your code doesn't spawn new ones), the Session will live for the whole request.
这将为每个线程提供一个唯一的会话。由于 servlet 请求总是在一个线程中处理(假设您的代码不会产生新的),因此 Session 将为整个请求而存在。
Don't forget to use a filter to close the Session after the request!
不要忘记在请求后使用过滤器关闭会话!