org.hibernate.HibernateException: save is not valid without active transaction

六月ゝ 毕业季﹏ 提交于 2019-12-04 03:21:28

You have to call session.beginTransaction()

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

Try changing your method to be as follows:

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

Should solve your problem.

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 part yourself.

I think you'll find something like this 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 "close" the transaction, you can close the session, as you can see. Read this here, it might be useful for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!