Reputation: 2078
I have two entities User and Department, There is a bidirectional relation between the two entities (OneToMany and ManyToOne), I manage the relationship in a service class that handles removing and adding users to department in the following:
List<User> originalUserList = userJpaRepository.findAllByDepartment(department);
for (Iterator<User> iterator = originalUserList.iterator(); iterator.hasNext();) {
User user = iterator.next();
if (!department.getDepartmentEmployees().contains(user)) {
user.setDepartment(null);
userJpaRepository.save(user);
}
}
for (User user : department.getDepartmentEmployees()) {
user.setDepartment(department);
userJpaRepository.save(user);
}
Department savedDepartmetn = jpaRepository.save(department);
return savedDepartmetn;
Everything works fine adding and removing users gets reflected to the database, but the only problem is in the second to last line, the isntance savedDepartment will still contain removed Users because hibernate populates its data from a select that happens before the changes done to user is actually flushed to the database. What is the best approach here,
Upvotes: 1
Views: 1908
Reputation: 692161
There is no need to save anything since you're using attached entities. JPA automatically persists the changes you do to attached entities.
And when you have a bidirectional association, it's your responsibility to make the changes at both sides to ensure that your object model is consistent. If you set user.department
to null, then you should also remove the user from department.users
.
I don't understand what the above code is doing, but remove the calls to save, and maintain both sides of the association, and everything will be fine.
Upvotes: 2