2017-06-29 58 views
0

我使用hibernate 5.2连接到SQLite库。我创建了一个新的Session,并在关闭我的Session之后使用session.createNativeQuery("My sql").executeUpdate()。一切正常,但我遇到几个例子,在创建Session后,他们开始Transaction,执行SQL操作,提交Transaction,并关闭Session。但并不是所有在线的例子都有Transaction,我的代码在没有它的情况下工作正常。Hibernate,如果beginTransaction不会被使用会发生什么?

这让我很好奇:

  • 为什么我们需要使用Transaction
  • 如果我们不会,会发生什么?
  • 而最重要的是,在哪些情况下需要使用并且其中 不是?

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

+1

这与Java或休眠没有任何关系。事务是一个数据库事情 – Jens

回答

0

您可以尝试将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?

0

为什么我们需要使用交易? - >你在做什么只是一个简单的更新,交易管理是用于万一有多个更新,你想为你的交易的ACID性质。

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

+0

我正在执行几个'SQL'查询没有'事务',它很好。你能否多说一些可能会出错的情况? – Alyona

0

让我们来定义什么是交易 - 基本上是工作的原子单位。有两种类型的事务管理或事务分界(将开始事务,提交或回滚事务划分为划分):CMT(容器管理事务) - 由底层容器管理(JTA)和BMT(bean)管理事务) - 事务划分由开发人员自己以编程方式管理。因此,如果您在任何示例中看到transaction已获得并以程序化方式提交或回滚 - 这就是BMT的示例,也就是说,您有责任让开发人员管理事务。

只要你没有看到显式的事务分界 - 这意味着是CMT。 这是一个非常广泛的主题 - 我劝你read more.

相关问题