java 为什么要使用 session.beginTransaction & transaction.commit
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10171856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why to use session.beginTransaction & transaction.commit
提问by krishna
Hibernate: If any Transient object was added into hibernate session, why can't hibernate persist it(after its dirty checking) when i close the session.
休眠:如果任何瞬态对象被添加到休眠会话中,为什么当我关闭会话时休眠不能持久化它(在它的脏检查之后)。
Is there any such of kind of option available. Also, if such option exists, then why we are beginning a transaction & saying it to commit. (session.beginTransaction() )
有没有这样的选择。此外,如果存在这样的选项,那么我们为什么要开始一个事务并说它要提交。(session.beginTransaction() )
what functionality that transaction.commit() does can also be done once we say session.close() right? Kindly any one explain me about this.
一旦我们说 session.close() 对,transaction.commit() 的什么功能也可以完成?请任何人向我解释这一点。
回答by axtavt
Transaction demarcationis essential for correct usage of RDBMS, that's why you need to start and commit transactions with Hibernate.
事务划分对于正确使用 RDBMS 至关重要,这就是您需要使用 Hibernate 启动和提交事务的原因。
Regarding your question, you cannot implicitly close transaction when you close the session, but there is a common practice to close the session as soon as you close the transaction. Hibernate provides special support for this pattern in form of contextual sessions.
关于您的问题,您不能在关闭会话时隐式关闭事务,但通常的做法是在关闭事务后立即关闭会话。Hibernate 以上下文会话的形式为这种模式提供了特殊的支持。
Some frameworks (Spring, EJB, etc) go further by eliminating the need to begin and commit transactions programmatically - they provide declarative transaction approach that allows you to mark a method as transactional declaratively. That is, they open contextual session (if needed) and begin transaction when you enter such a method, and commit the transaction and close the session (if needed) when you return from it.
一些框架(Spring、EJB 等)通过消除以编程方式开始和提交事务的需要而走得更远——它们提供了声明式事务方法,允许您以声明方式将方法标记为事务性。也就是说,当您输入这样的方法时,它们打开上下文会话(如果需要)并开始事务,并在您从它返回时提交事务并关闭会话(如果需要)。
回答by surajR
session.beginTransaction is used to start a transaction which may consists of one or more crude operations like INSERT,SELECT,DELETE etc. While transaction.commit() is used for committing all changes happened during a transaction so that database remains in consistent state after operations.
session.beginTransaction 用于启动一个事务,该事务可能包含一个或多个粗略的操作,如 INSERT、SELECT、DELETE 等。而 transaction.commit() 用于提交事务期间发生的所有更改,以便数据库在之后保持一致状态操作。