I'm fairly new to Hibernate, and have a question that I haven't been able to find an answer to.
I have a situation where I am loading a static array with objects from a hibernate query, these objects are immutable, so will never be modified.
All examples I have found, as well as documentation shows starting a transaction before executing the query, and after the query is complete executing the commit() method on the transaction.
My question is, in this situation, is the transaction and the commit() necessary? I have tried it without, and it does work and improves performance. Is there any reason why it should not be done this way? Below are two examples of the same method one with and one without the transactions.
example with transaction and commit():
Code:
private static void loadSecurityRoles()
throws MyApplicationException {
Transaction tx = null;
try {
Session session = HibernateUtil.currentSession();
tx = session.beginTransaction();
Query query = session.createQuery(
"from SecurityRole order by Description ");
securityRoles = (SecurityRole[])query.list()
.toArray(
new SecurityRole[] {});
tx.commit();
} catch (Exception e) {
HibernateUtil.rollback(tx);
throw new MyApplication(
"Error loading security role descriptions",
e);
}
}
example without transaction and commit():
Code:
private static void loadSecurityRoles()
throws MyApplicationException {
try {
Session session = HibernateUtil.currentSession();
Query query = session.createQuery(
"from SecurityRole order by Description ");
securityRoles = (SecurityRole[])query.list()
.toArray(
new SecurityRole[] {});
} catch (Exception e) {
throw new MyApplicationException(
"Error loading security role descriptions",
e);
}
}
Any thoughts on the benefits/drawbacks to either option? While in this example, this code is only hit once during execution of the application, there are similar instances where the code is executed several times and there is a considerable performance hit when the transaction with the commit() is used.
Thanks for any help/advice on this matter.