I am trying to utilize Hibernate and am trying to avoid the management of session by utilizing the getCurrentSession()
which is provided by the API SessionFactory
. As I understand it, this will manage the session for me. My problem is when trying to use it in place of openSession()
, I am getting an error saying that I need to have an active transaction. Online i have read conflicting answers, so i am still not sure. I am trying to execute a read only query (basically a select), why do i need a transaction for that?
Error message: org.hibernate.HibernateException message: getNamedQuery is not valid without active transaction
More details:
Hibernate.cfg.xml - snippet
<hibernate-configuration>
<session-factory name="hibernateSessionFactory">
<property name="connection.datasource">jdbc/DPARISC</property>
<property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<property name="hibernate.connection.isolation">1</property>
Nothing special in the way we create the SessionFactory
config.buildSessionFactory();
Now here is where the problem comes, on the createQuery
Session session = HibernateUtil.getDB2SessionFactory().getCurrentSession();
Query query = session.createQuery(queryStringBuilder.toString())
.setParameter("orgId", request.getOrgId().intValue())
.setParameter("busUnitId", request.getBusinessUnitId().intValue());
query.setMaxResults(HibernateConstants.MAX_RESULTS);
Again the query is basically just a Select statement. Do i need to have a begin transaction and then a commit even for things like this when i use getCurrentSession()
? Isnt that going to create a lot of overhead?
Short answers for your questions: yes and no.
Longer answers:
Hibernate requires you to have a session open when you perform anything. You can use getCurrentSession()
only if you actually have opened one.
Why do you assume it creates a lot of overhead?