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.
1 Answer 1
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();
}
}
Explore related questions
See similar questions with these tags.