我的hibernate事务和会话有什么问题

olhwl3o2  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(175)

代码如下:

class HibernateTest {

public static void main(final String[] args) {
    final HibernateTest objHibernateTest = new HibernateTest();
    
    objHibernateTest.saveEmployeeDetails();
    
    objHibernateTest.saveEmployeeLeaves();
    
    objHibernateTest.saveEmployeePayment();
}

private void saveEmployeeDetails() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();//Begin Transaction
    Employee e = new Employee();//consider Employee have data
    session.update(e);
    session.flush();
    session.clear();
}

private void saveEmployeeLeaves() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Employee e = new Employee();//consider Employee have data
    session.save(e);
    session.flush();
    session.clear();
}

private void saveEmployeePayment() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Employee e = new Employee();//consider Employee have data
    session.save(e);
    session.flush();
    session.getTransaction().commit();//Commit Transaction
}
}

在上面的代码中,我首先调用saveEmployeeDetails(),在那里我获得会话并开始事务,然后调用flush() and clear()用于缓存目的。
我在saveEmployeeLeaves()中做了同样的事情。
在函数saveEmployeePayment()中,我执行了一些操作并保存了员工的详细信息。
但是在这个场景中,只有Payment的详细信息存储在db中,而不是Employee detailsLeave details
为什么会这样?

lndjwyie

lndjwyie1#

每次更新都需要提交事务。在最后一个方法调用中进行更新不会提交之前的所有内容。session变量的作用域仅限于方法块。

private void saveEmployeeDetails() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();//Begin Transaction
    Employee e = new Employee();//consider Employee have data
    session.update(e);
    session.flush();
    session.getTransaction().commit(); // Commit after update
    session.clear();
}

private void saveEmployeeLeaves() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Employee e = new Employee();//consider Employee have data
    session.save(e);
    session.flush();
    session.getTransaction().commit(); //Commit after update
    session.clear();
}

private void saveEmployeePayment() {
    final Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Employee e = new Employee();//consider Employee have data
    session.save(e);
    session.flush();
    session.getTransaction().commit();//Commit Transaction
}

相关问题