1
\$\begingroup\$

We are new into hibernate, in our project for saving an entry the below given code is used, please have a look.

public void save(Object obj) {
    Session session = null;
    Transaction transaction = null;
    try {
        session = sessionFactory.getCurrentSession();
        transaction = session.beginTransaction();
        session.save(obj);
        session.flush();
        transaction.commit();
    } catch (JDBCException jde) {
        logger.fatal("Error occured in database communication", jde);
        transaction.rollback();
        throw new RuntimeException(jde);
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
}

Is this the right way to do (Considering performance and Security) ? Is this thread safe? as there may be number of users at the same time.

Bonus Question:is there any way to make this code better in Java 8 ?


ps:This method is written in our DatabaseUtil class.

\$\endgroup\$
1
\$\begingroup\$

Your finally should strive to be as safe as it can, since you may have already had some error occur. To that end, you could run into trouble with a null pointer:

} finally {
    if (session.isOpen()) {
        session.close();
    }
}

If session is null then you've just caused another error, so test session before you call on it:

} finally {
    if (session != null && session.isOpen()) {
        session.close();
    }
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.