hibernate session.save() does not reflect in database

后端 未结 9 2120
臣服心动
臣服心动 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:15

    I was also trying to understand the point: save() can perform Insert operation outside transaction boundary so I did something like this

    SessionFactory factory = new Configuration().configure()
                        .buildSessionFactory();
                Session session = factory.openSession();
    
                session.save(user);
    
                session.close();
    

    But data not inserted in database.So I again tried this and now it worked for me and data inserted sucessfully:

    in configuration file:

      <property name="connection.autocommit">true</property>
    

    and in java code:

        SessionFactory factory = new Configuration().configure()
                .buildSessionFactory();
        Session session = factory.openSession();
    
        session.save(user);
    
        session.flush();
        session.close();
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-08 15:21
    if there is DB manipulation operation then it should be in transaction
    if you call session.save(object)
    hibernate create bellow query only .
    select hibernate_sequence.nextval from dual
    so right code is here
    Transaction  t=session.beginTransaction();
    session.save(obect);
    t.commit(); should not forgot to commit.
    session.close();
    
    0 讨论(0)
提交回复
热议问题