简体   繁体   English

休眠会话与事务

[英]Hibernate Session vs Transaction

I'm a bit confused about the concept of Sessions and Transactions in Hibernate.我对 Hibernate 中的会话和事务的概念有点困惑。 As far as i understand, Hibernate uses Sessions (Persistence Context), which is basically a Cache for Entitys that need to be persist, deleted or whatever in the Database.据我了解,Hibernate 使用会话(持久性上下文),它基本上是需要在数据库中持久化、删除或其他任何实体的缓存。 Sessions encapsulate Transactions, so i start a Session, followed by creating a Transaction.会话封装了事务,所以我启动一个会话,然后创建一个事务。 After the Transaction is closed, everything from the Persistence Context is flushed to the Database.The same thing will happen, if i close the Session.关闭事务后,持久性上下文中的所有内容都会刷新到数据库。如果我关闭会话,也会发生同样的事情。

Why do i need both?为什么我两者都需要? Can i do the same without creating a Transaction?我可以在不创建交易的情况下做同样的事情吗?

First of all, you can open more than 1 transaction within the same session.首先,您可以在同一个会话中打开多个事务。

Now, flushing doesn't necessarily relate to transaction commit.现在,刷新不一定与事务提交有关。 When you save() an entity - it'll be flushed if you use Identity generation strategy.当您save()一个实体时 - 如果您使用身份生成策略,它将被刷新。 When you select something - Session will also flush (if flush mode is AUTO).当您select某些内容时 - 会话也将刷新(如果刷新模式为自动)。 And you can even tell Hibernate not to flush before transaction commits (flush mode MANUAL).您甚至可以告诉 Hibernate 在事务提交之前不要刷新(刷新模式 MANUAL)。

Transactions are only responsible for ACID, it's a DB feature.事务只对 ACID 负责,它是一个 DB 特性。 While Session is responsible for managing entities, generating SQL, handling events.而Session负责管理实体,生成SQL,处理事件。 It's a Java thing.这是Java的事情。

PS: Session isn't just a "cache". PS:会话不仅仅是一个“缓存”。 It's also a way to track which entities are changed.这也是一种跟踪更改了哪些实体的方法。 So it's more than just an optimization trick.所以这不仅仅是一个优化技巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM