Reputation: 23
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
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 DISCONNECT
ed at the end.
Upvotes: 0
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
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