A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of the following three states at a given point in time:
Session session =factory.openSession();
Transactiontx=null; try{ tx= session.beginTransaction(); // do some work ... tx.commit(); } catch(Exception e){ if(tx!=null) tx.rollback(); e.printStackTrace(); }finally{ session.close(); } If the Session throws an exception, the transaction must be rolled back and the session must be discarded. |