Search code examples
javahibernateobjectormpersistent

Hibernate multiple object update in same session


Using Hibernate I need to update multiple objects by calling for eg. updateDetails() function shown below:

function updateDetails(){   
        Session session = this.getSessionFactory().openSession();           
        Employee emp=(Employee )session.load(Employee.class, empId);
        emp.salary(2000);
        Account acc=(Account)session.load(Account.class, accId);
        account.setTotal(2000);
        Transaction tx=session.beginTransaction();      
        session.update(emp);
        session.update(acc);
        tx.commit();
        result=true;
        session.close();

}

what is the best way of doing this ?

does Updating multiple objects of same or different type in same session will cause any problem in hibernate?


Solution

  • Why not. You can do that. Hibernate allows.

    Since you are using Transaction management the answer is depends on your context. If you want to save both Objects regardless of saving another make them update in individual transactions.

    If you want to save the whole info successfully and want to revert everything if any of the update fail keep them in the current format.