【问题标题】:Hibernate, what will happen if beginTransaction won't be used?Hibernate,如果不使用 beginTransaction 会发生什么?
【发布时间】:2017-12-03 00:15:22
【问题描述】:

我正在使用休眠 5.2 连接到 SQLite 库。我创建了一个新的Session 并在关闭Session 之后使用了session.createNativeQuery("My sql").executeUpdate()。一切正常,但我遇到了几个例子,在创建Session 之后,它们开始Transaction,执行SQL 操作,提交Transaction,然后关闭Session。但并非所有在线示例都有Transaction,没有它我的代码也能正常工作。

这让我很好奇:

  • 为什么我们需要使用Transaction
  • 如果我们不这样做会怎样?
  • 最重要的是,在哪些情况下需要使用它以及在哪些情况下使用它 不是吗?

我用<property name="hibernate.connection.pool_size">1</property>

【问题讨论】:

  • 这与 Java 或休眠无关。事务是数据库的事情

标签: java sql hibernate session transactions


【解决方案1】:

为什么我们需要使用事务? -> 您所做的只是一个简单的更新,事务管理用于以防有多个更新并且您希望事务具有 ACID 特性。

如果我们不这样做会发生什么? -> 如果有多个更新语句并且其中一个抛出异常,您将得到不一致的数据。

【讨论】:

  • 我在没有Transaction 的情况下执行了几个SQL 查询,结果很好。你能多谈谈它可能出错的情况吗?
  • Alyona 有冲突可序列化之类的概念,dhanajay 指的是那些
【解决方案2】:

您可以尝试将 hibernate 与 JDBC 关联起来,您将获得一些关于事务的提示。

在 JDBC 中,您只需打开一个连接即可开始工作,最后您可以提交或回滚。

但是,如果您有许多不同的并行任务,它们可能相互依赖或独立。然后您可能需要单独提交/回滚每个任务,或者如果有任何失败则回滚。

for example
Big Task :
    small task1
    small task2
    small task3 and many more

如果任何小任务失败,则回滚大任务。这可能是众多业务需求之一。

在JDBC中,Connection接口提供了commit()和rollback()方法。

在jpa/hibernate中,Transaction接口提供了commit()和rollback()方法。

所以一个会话可以有许多相关或独立的事务。

以下是来自 org.hibernate.Transaction 的文档

Allows the application to define units of work, while maintaining 
abstraction from the underlying transaction implementation (eg. JTA, JDBC). 

A transaction is associated with a Session and is usually 
initiated by a call to org.hibernate.Session.beginTransaction(). 
A single session might span multiple transactions since the notion of a session 
(a conversation between the application and the datastore) is of coarser granularity 
than the notion of a transaction. However, it is intended that there be at most 
one uncommitted transaction associated with a particular Session at any time. 

这也可能对您有所帮助 What is the difference between a session and a transaction in JPA 2.0?

【讨论】:

    【解决方案3】:

    让我们定义什么是事务 - 基本上它是工作的原子单元。

    有两种类型的事务管理或事务划分(将划分视为启动事务、提交或回滚事务):CMT(容器管理事务)-由底层容器为您管理(JTA)和 BMT(bean 管理事务) - 事务分界由开发人员自己以编程方式管理。因此,如果您在任何示例中看到transaction 被获取并以编程方式提交或回滚 - 这就是 BMT 的示例,那就是开发人员有责任管理事务。

    当您没有看到明确的事务划分时 - 这意味着这就是 CMT。 这是一个非常广泛的主题 - 我建议你 read more.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 2019-07-06
      • 2012-01-13
      相关资源
      最近更新 更多