I wrote the below code to retrieve data from the data base, in that do we need to begin the transaction? Because it runs without any issue. Is it necessary to use it every time? Will it cause any problem in future without that?
public static Student getStudentById(long id) {
Session session = null;
Student student = null;
//Transaction transaction=null;
try {
session = HibernateUtil.getSessionFactory().openSession();
//transaction = session.getTransaction();
//transaction.begin();
/**
* names in the query should match the related class name and variable names.
*/
Query query = session.createQuery("from Student where studentId = :id");
query.setLong("id", id);
student = (Student) query.uniqueResult();
//transaction.commit();
} catch (HibernateException e) {
//transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return student;
}
No, you don’t need to use transaction unless and until you are planning to persist the data inside the db. And In your question you are not persisting the date you are just fetching the records from the db. So here not mandatory to use transaction.