0

我有如下代码。

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详细信息才会存储在数据库中Employee details,而不是Leave details

为什么会这样?

先谢谢了......

4

1 回答 1

1

您需要为每次更新提交事务。在最后一个方法调用中更新不会提交之前的所有内容。您的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
}
于 2013-10-10T05:52:00.560 回答