hibernate session.save() does not reflect in database

后端 未结 9 2125
臣服心动
臣服心动 2020-12-08 14:30

According to my understanding in hibernate (please confirm)

1- You have to session.close() if you get it by getSessionFactory().openSession()

9条回答
  •  执念已碎
    2020-12-08 15:19

    session.close() is only responsible to close the session https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#close()

    how to work with hibernate session: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-basics

    // Non-managed environment idiom
    Session sess = factory.openSession();
    Transaction tx = null;
    try {
        tx = sess.beginTransaction();
    
        // do some work
        ...
    
        tx.commit();
    }
    
    catch (RuntimeException e) {
        if (tx != null) tx.rollback();
        throw e; // or display error message
    }
    finally {
        sess.close();
    }
    

    As it wrote in the documentation: a much more flexible solution is Hibernate's built-in "current session" context management:

    // Non-managed environment idiom with getCurrentSession()
    try {
        factory.getCurrentSession().beginTransaction();
    
        // do some work
        ...
    
        factory.getCurrentSession().getTransaction().commit();
    }
    catch (RuntimeException e) {
        factory.getCurrentSession().getTransaction().rollback();
        throw e; // or display error message
    }
    

提交回复
热议问题