Hibernate是否支持嵌套事务? [英] Does Hibernate support nested transactions?

查看:594
本文介绍了Hibernate是否支持嵌套事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的话:

 开始交易1 
调用someMethod
开始交易2
调用someOtherMethod
开始tranaction3

如果transaction3回退,transaction2和transaction1是否也回滚?



感谢!

解决方案

Hibernate没有明确支持嵌套事务,使用能够创建保存点的JDBC 3.0驱动程序可以实现此目的。



创建连接在程序开始时创建 SessionFactory 。此时,您还创建了一个 Savepoint 作为交易的起点。

然后您移动每个嵌套事务。对于每个嵌套事务,您应该创建另一个不同的savePoint,即一个rollingSavePoint,如果嵌套事务失败,您可以回滚它。然后,对于同一嵌套事务,打开一个会话,该会话使用您在开始时创建的 Connection (即Session nestedTransaction = SessionFactory.openSession(connection)) 并进行更新。刷新会话并关闭它。



完成所有嵌套事务后,调用 connection.commit()来提交全球交易并关闭它。



需要注意的一些事项:


  • 显然autoCommit模式必须关闭,否则每次调用flush时,都会直接提交给数据库。

  • 如果您还在搜索或其他操作,您将希望打开使用自己的连接的其他会话。确保将事务隔离级别设置为 READ_UNCOMMITED ,否则您可能会遇到锁定问题。 当然,您应该提交定期或否则您的数据库将有问题,或者您可以增加数据库虚拟内存的大小。



如果您使用的是spring,也使用Spring Propagation.Check this link
http:// www。 byteslounge.com/tutorials/spring-transaction-propagation-tutorial


If I have this:

Start transaction1
  Call someMethod
    Start transaction2
       Call someOtherMethod
          Start tranaction3

If transaction3 rolls back, do transaction2 and transaction1 roll back also?

Thanks!

解决方案

While Hibernate does not explicitly support nested transactions, using a JDBC 3.0 driver that is able to create savepoints can achieve this.

Create a Connection at the start of the program when the SessionFactory is created. At this point you also create a Savepoint that serves as the starting point for the transaction.

Then you move through each nested transaction. For each nested transaction, you should create another different savePoint i.e. a rollingSavePoint which you can rollback to should that nested transaction fail. Then for that same nested transaction, open a session that uses the Connection you created at the start (i.e. Session nestedTransaction = SessionFactory.openSession(connection)) and make your updates. Flush the session and close it.

After all nested transactions are completed, call connection.commit() to commit the global transaction and close it. Close the sessionFactory as per usual and continue to do whatever else you need to do.

Some things to note:

  • Obviously autoCommit mode must be off, otherwise each time you call flush you'll be commiting straight to the DB.
  • If you're also doing searching or other operations you'll want to open other sessions that use their own connections. Ensure that you set the Transaction isolation level to READ_UNCOMMITED or else you'll probably be facing locking problems.
  • Of course you should commit periodically or else your database will have issues, or you can increase the size of database virtual memory.

If you are using spring you can also use Spring Propagation.Check this link http://www.byteslounge.com/tutorials/spring-transaction-propagation-tutorial

这篇关于Hibernate是否支持嵌套事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆