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.

asked Feb 18, 2016 at 9:48
\$\endgroup\$
0

1 Answer 1

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();
 }
}
answered Feb 18, 2016 at 10:38
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.