[ACCEPTED]-org.hibernate.HibernateException: save is not valid without active transaction-persistence

Accepted answer
Score: 23

You have to call session.beginTransaction()

public void create(T entity) {
   Session session=getSessionFactory().getCurrentSession();
   Transaction trans=session.beginTransaction();
   session.save(entity);
   trans.commit();
}

0

Score: 3

Try changing your method to be as follows:

public void create(T entity) {
    getSessionFactory().getCurrentSession().beginTransaction();
    getSessionFactory().getCurrentSession().save(entity);
    getSessionFactory().getCurrentSession().endTransaction();
}

Should 1 solve your problem.

Score: 3

Do it like this:

  public void create(T entity) {
       org.hibernate.Session ss= getSessionFactory().getCurrentSession();
       Transaction tx=ss.beginTransaction();
       ss.save(entity);
       tx.commit();    
  }

Do the exception handling 1 part yourself.

Score: 2

I think you'll find something like this 4 is more robust and appropriate:

Session session = factory.openSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();

   // Do some work like:
   //session.load(...);
   //session.persist(...);
   //session.save(...);

   tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
   tx.rollback();
   throw e; // or display error message
}
finally {
    session.close();
}

You cannot 3 "close" the transaction, you can 2 close the session, as you can see. Read 1 this here, it might be useful for you.

More Related questions