krishna
krishna

Reputation: 837

why to use session.beginTransaction & transaction.commit

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() )

what functionality that transaction.commit() does can also be done once we say session.close() right? Kindly any one explain me about this.

Upvotes: 4

Views: 17302

Answers (2)

surajR
surajR

Reputation: 573

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.

Upvotes: 1

axtavt
axtavt

Reputation: 242686

Transaction demarcation is essential for correct usage of RDBMS, that's why you need to start and commit transactions with 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.

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.

Upvotes: 3

Related Questions