gpt4 book ai didi

Hibernate - 使用编程事务惯用语的 CMT EJB

转载 作者:行者123 更新时间:2023-12-01 22:04:30 25 4
gpt4 key购买 nike

在 CMT (EJB3) 中使用以下编程事务和 session 习惯用法并且将 Hibernate Core 设置为使用 CMT 时会发生什么?
假设需要当前 CMT 事务并使用默认的 @TransactionAttribute(REQUIRED)

  1. hibernate 事务会在 beginTransaction() 上加入当前 CMT 吗?
  2. commit() 会尝试立即提交 hibernate 事务还是等到当前 CMT 提交?
  3. 在 CMT 中关闭 session 时会发生什么?

B.该行为是否取决于当前 session 是否使用 getCurrentSession() 绑定(bind)到 CMT?

// A: openSession()
// B: getCurrentSession();
Session session = sessionFactory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();

// do some work

tx.commit();
}
catch (final RuntimeException e)
{
try
{
tx.rollback();
}
catch (final RuntimeException e)
{
// log error
}
throw e;
}
finally
{
session.close();
}

在我的应用程序中,目前我使用单个数据库,并且使用 Hibernate 的编程 JDBC 事务可以很好地工作。现在,应用程序还使用 JMS 队列进行邮件消息传递,并希望将其合并到全局 CMT 事务中。

编辑:

目前,我根本没有在应用程序中使用 EntityManager,并且还希望将代码移植到非托管环境。

Hibernate 配置 hibernate.cfg.xml 以启用 CMT:

Hibernate 4.2.6 和 Glassfish 3.1.2

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.connection.datasource">jdbc/datasource</property>
<property name="hibernate.current_session_context_class">jta</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property>
<property name="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.SunOneJtaPlatform</property>

SessionFactory检索

SessionFactory 是在单例 EJB 中构建的。 删除不必要的东西。

@Startup
@Singleton
public class SessionManager
{
private SessionFactory sessionFactory;

public SessionManager()
{
final Configuration configuration = new Configuration().configure();
this.sessionFactory = configuration.buildSessionFactory();
}
}

最佳答案

正如 Luk 所指出的,这不是在 CMT 环境中编码的方法。无论如何,根据 session.beginTransaction() 部分在这里是安全的 http://docs.jboss.org/hibernate/annotations/3.5/api/org/hibernate/Session.html#beginTransaction%28%29其中说

If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction

tx.rollback() 也是安全的。文档中没有说明,但 CMTTransaction 实际上执行 getTransaction().setRollbackOnly(),即它只是将 TX 标记为回滚。提交实际上不会提交 TX,但可能会刷新 session 。如果涉及多个资源,真正的提交将违反事务语义。

关于Hibernate - 使用编程事务惯用语的 CMT EJB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com