Yasser Shaderma
Yasser Shaderma

Reputation: 23

Difference between SessionFactory.openSession() & SessionFactory.getCurrentTransaction().commit()

what would happen if I close the session with Session.getCurrentTransaction().commit() or close the session with session.close() at the end of my method?

public static void deleteYear(Years year)
{
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.delete(year);
            // what is the best way to close session
    session.getTransaction().commit();
            //or : session.close(); ???
}

Upvotes: 2

Views: 2692

Answers (3)

Matin Kh
Matin Kh

Reputation: 5178

These are two different things totally.

COMMIT makes the changes which have taken place within the transaction so far.
CLOSE closes the session, and you no longer have access to that session.

So you can have both together.

A note to remember: Closing a session is not necessary; however, a session should be DISCONNECTed at the end.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

ASAIK, these two are entirely different operations.

sessionFactory.openSession(): It opens a session

session.beginTransaction(): It begins a transaction, a transaction is a atomic unit of work which should succeed or fail entirely.

session.getTransaction().commit(): It commit the transaction, means all the things happened between beginTransaction and this call will get persisted to database. If you doesn't commit a transaction then all the changes happened in the transaction will be lost. Commiting a transaction deosn't close the session

session.close(): closes the session and releases the acquired resources.

That means you need to call both commit() and session.close().

public static void deleteYear(Years year)
{
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.delete(year);
    session.getTransaction().commit();
    session.close();
}

Upvotes: 4

Suresh Atta
Suresh Atta

Reputation: 121998

Better way to do session transactions

Session sess=getSession();
Transcration tx=sess.beginTranscration();
//do something with session
sess.save(obj);
tx.commit();
sess.close;

And i am recommending this .

Upvotes: 0

Related Questions