lee
lee

Reputation: 246

Working of hibernate. Is it necessary to use transaction every time? Will it cause any issue if i dont use it while retieving data?

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;
}

Upvotes: 2

Views: 2946

Answers (2)

Jay
Jay

Reputation: 681

According to hibernate documentation Database, or system, transaction boundaries are always necessary. No communication with the database can occur outside of a database transaction (this seems to confuse many developers who are used to the auto-commit mode). Always use clear transaction boundaries, even for read-only operations. Depending on your isolation level and database capabilities this might not be required, but there is no downside if you always demarcate transactions explicitly. Certainly, a single database transaction is going to perform better than many small transactions, even for reading data.

You can refer hibernate documentation here.

Upvotes: 8

subodh
subodh

Reputation: 6158

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.

Upvotes: 0

Related Questions