gpt4 book ai didi

java - 事务在 Hibernate 中是可选的。但为什么我们每次都需要使用它呢?还有其他选择吗?

转载 作者:行者123 更新时间:2023-12-01 21:15:47 25 4
gpt4 key购买 nike

我发现使用事务是可选的,因为 hibernate 应用程序在自己的应用程序代码中管理事务。但是当我尝试在没有事务的情况下执行代码时,代码执行时没有任何错误,但数据库中没有数据。如何在不使用事务的情况下提交数据(因为它是可选的)?事务的替代方案是什么?

 Configuration c = new Configuration();
c.configure("hibernate.cfg.xml");
SessionFactory sf = c.buildSessionFactory();

Session s = sf.openSession();

//Transaction t = s.beginTransaction();
//some code
//t.commit();

最佳答案

Database, or system, transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations (c) Hibernate transaction demarcation doc

有文档说 Transaction 是可选的。

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional. Basic API's / architecture doc

这实际上意味着如果您在为您进行事务划分的环境(容器/框架)中运行代码 - 您可以为此跳过使用 Hibernate API

此 API 的替代方案是 Spring Declarative Transaction management (基本上是注释,它们也有 XML 方式),Transaction demarcation in an EJB container等 - 这些取决于您运行代码的位置。

事务是数据库的基本工作单元,它们是工作数据库所必需的,使用数据库的人应该始终指定事务开始/结束的位置。

您可以在 ACID guarantees 上阅读更多内容对于某些上下文。

关于java - 事务在 Hibernate 中是可选的。但为什么我们每次都需要使用它呢?还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40191881/

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