12

I'm new to Hibernate.

  • Automatically created hibernate.cfg.xml (Netbeans wizard)
  • Automatically created HibernateUtil.java
  • Automatically created POJO class with annotations

Trying to get object from database but getting error:

Exception in thread "pool-1-thread-1" org.hibernate.HibernateException: get is not valid without active transaction
    at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:297)

getting an object:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);

hibernate.cfg.xml

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sochi_feedback</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
VextoR
  • 5,087
  • 22
  • 74
  • 109

4 Answers4

16

Add

Transaction tx = session.beginTransaction(); //This statement will initiate the transaction

just before your CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);

and at the end of your transaction commit the changes by calling..

tx.commit();
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54
7

Another solution is to use openSession() instead of getCurrentSession(). Then transactions can be used only when required for updating queries.

Session session = HibernateUtil.getSessionFactory().openSession();
CallInfo ci = (CallInfo) session.get(CallInfo.class, ucid);
Amil Waduwawara
  • 1,632
  • 1
  • 16
  • 14
  • I'm experiencing exactly this, i.e. that sessions obtained via getCurrentSession requires a transaction even for get-operations, whereas this does not apply when using openSession. Why is that? (I had thought that the session-objects are identical?) – thomas a. h. Sep 06 '17 at 07:57
  • I had the same issue. But why? –  Nov 16 '17 at 03:07
0

Even after beginTransaction() and and commit() if you still get the

Caused by: org.hibernate.HibernateException: setDefaultReadOnly is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352) 

go to "Start" and search for services and restart the database service

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
prasad
  • 3
  • 5
0

Before you actually start the transaction you need to start the session by calling session.beginTransaction(), right after you create sessionFactory.

Farruh Habibullaev
  • 2,342
  • 1
  • 26
  • 33