my requirement is that i want to
save an object and
after saving it
update that object with other related data (all in
same transaction, since i am using
@Transcational annotation on
service class level), here's a code snippet:
-
Service: Code:
@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:Code:
public class MyDao {
public void addEmployee(Employee employee) {
employee = (Employee) getCurrentSession().merge(employee);
getCurrentSession().save(employee);
}
public void updateEmployee(Employee employee) {
getCurrentSession().update(employee);
}
}
ISSUE: in the service, after saving the object and trying to update,i found out that the id of the saved object is 0 so it suppose that it's not saved, so it tries to insert it again, so what is the best way to avoid that, merging then saving all at once ? or make the add and the update in separate transactions ?
please advise, thanks.