在同一事务中保存并更新对象

时间:2011-12-04 23:16:10

标签: hibernate java-ee

我的要求是我要保存一个对象,保存后 更新该对象与其他相关数据(全部在同一交易,因为我在服务类级别上使用 @Transcational 注释),这是一个代码段:

服务:

@Service@Transactional
public class MyService {

    public Employee addEmployee(Employee employee) throws Exception, {

        try {

            employeeDao.addEmployee(employee);

            MessagingGroup messagingGroup = messageGroupDao.getMsgGroupByID(1);
            EmployeeGroup employeeGroup = new EmployeeGroup();
            employeeGroup.setEmployee(employee); // the saved employee
            employeeGroup.setMessageGroup(messagingGroup);
            employeeGroup.setJoinType(false);
            Set < EmployeeGroup > employeeGroups = new HashSet < EmployeeGroup > ();
            employeeGroups.add(employeeGroup);

            employee.setEmployeeGroups(employeeGroups);
            updateEmployee(employee);

            return employee;
        } catch (AccessDeniedException ad) {
            throw new AccessDeniedException("Access Denied!");
        } catch (Exception e) {
            log.error("Error Occurred While Adding Employee: " + e.getMessage());
            e.printStackTrace();
            return null;
        }

    }
}

DAO:

public class MyDao {

    public void addEmployee(Employee employee) {
        employee = (Employee) getCurrentSession().merge(employee);
        getCurrentSession().save(employee);
    }

    public void updateEmployee(Employee employee) {
        getCurrentSession().update(employee);
    }

}

问题:

在服务中,保存对象并尝试更新后,我发现保存对象的ID为0,因此它假设它没有保存(我想是因为事务在更新之前尚未提交,因为两者都是保存和更新是在同一个事务中),所以它试图再次插入它,那么避免这种情况的最佳方法是什么,合并然后立即保存所有?或者在单独的事务中进行添加和更新,或使用saveOrUpdate方法?我很困惑。

请告知,谢谢。

2 个答案:

答案 0 :(得分:0)

我认为你也应该尝试在你的Dao上使用@Transactional注释。

答案 1 :(得分:0)

通过更改save dao方法来修复它以返回保存的对象(带有生成的标识符):

public Employee addEmployee(Employee employee) {
            employee = (Employee) getCurrentSession().merge(employee);
            getCurrentSession().save(employee);
            return employee;
        }

并在服务中:

            employee=employeeDao.addEmployee(employee); // to get the generated identifier

            MessagingGroup messagingGroup = messageGroupDao.getMsgGroupByID(1);
            EmployeeGroup employeeGroup = new EmployeeGroup();
            employeeGroup.setEmployee(employee); // the saved employee
            employeeGroup.setMessageGroup(messagingGroup);
            employeeGroup.setJoinType(false);
            Set < EmployeeGroup > employeeGroups = new HashSet < EmployeeGroup > ();
            employeeGroups.add(employeeGroup);

            employee.setEmployeeGroups(employeeGroups);
            updateEmployee(employee);