RK3
RK3

Reputation: 1269

hibernate-- org.hibernate.TransactionException: Transaction not successfully started

am a beginner in hibernate. when am trying to save an object into the DB for which the table is not present. Am getting an exception org.hibernate.TransactionException: Transaction not successfully started at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:170) at org.rk.hibernate.HibernateTest.main(HibernateTest.java:20)

this is my class file where am trying to save the object into DB

package org.rk.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.rk.dto.UserDetails;

public class HibernateTest {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("GNS");
        try {       
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session session = sf.openSession();
            session.save(user);
            session.getTransaction().commit();
        }
        catch(HibernateException e) {
            e.printStackTrace();
            System.out.println("in exception");
        }
    }
}

Am using oracle 11g release 2 and hibernate 4.2.4 .. Please help

Upvotes: 3

Views: 32584

Answers (3)

Shruthi H R
Shruthi H R

Reputation: 7

I had added two TransactionManager , one is created using below code

  1. Transaction txn=session.beginTransaction();

another one was

  1. HibernateTransactionManager.

I resolved issue by removing removing Transaction txn=session.beginTransaction();

so that there is only one Transaction Manager in my code.

Upvotes: 1

omerhakanbilici
omerhakanbilici

Reputation: 963

In order to avoid org.hibernate.TransactionException you can use following code. Before committing it, you can control if it was committed. Difference is at 5th line !tx.wasCommited()

try {
  // create session
  tx = session.beginTransaction();
  // do something
  if (!tx.wasCommitted()){
    tx.commit();
  }
} catch (Exception exp) {
  tx.rollback();
  // close session
}

Upvotes: 8

QuestionEverything
QuestionEverything

Reputation: 5137

I think you are not beginning your transaction anywhere. You have opened a session, but before beginning transaction, you are committing it. Try beginning it after you open the session.

Like this:

try {
    // create session
    tx = session.beginTransaction();
    // do something
    tx.commit();
} catch (Exception exp) {
    tx.rollback();
    // close session
}

Upvotes: 18

Related Questions