why to use session.beginTransaction & transaction.commit

13,403

Solution 1

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.

Solution 2

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.

Share:
13,403
krishna
Author by

krishna

Updated on June 04, 2022

Comments

  • krishna
    krishna almost 2 years

    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.