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

时间:2013-10-10 05:29:34

标签: java hibernate

我的代码如下。

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

为什么会这样?

感谢高级......

1 个答案:

答案 0 :(得分: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
}