Reputation: 1073
I'm using OneToMany mapping in my SpringBoot project, while I'm having problems when updating the children along with parent update, sample code is like below:
User.java
@Table(name = "user")
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
@OneToMany(mappedBy = "groupUser", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<UserGroup> userGroups = new ArrayList<>();
}
UserGroup.java
@Table(name = "user_group")
@Entity
public class UserGroup {
@Id
@GeneratedValue
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="user_id")
private User groupUser;
}
SampleUsageCode.java
@Service
public class UserService {
@Autowired
private UserRepository userRepositry;
@Transactaional
public batchUpdateUsers(Collection<User> toBeSavedUsers) {
Map<Integer, User> toBeSavedIdUserMap = toBeSavedUsers.stream()
.collect(groupBy(User::getId(), toList()));
Collection<User> existingUsers = userRepositry.findByIdIn(toBeSavedIdUserMap.entrySet().stream()
.map(Map.Entry::getKey).collect(toList()));
existingUsers.forEach(user -> user.getUserGroups().add(toBeSavedIdUserMap.get(user.getId()).getUserGroups()));
}
}
To simplify the problem, Let's just assume the user groups in to-be-saved users is totally different with the existing ones in the database. The problem is when I try to add new user groups to existing users, it throws java.lang.UnsupportedOperationException
. It seems the persistentBag
type of userGroups
in User
is not editable.
I tried with just creating a new collection to store both existing and new user groups, but another error with A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance
occurs when I try to save the updated users. How can I achieve this cascading-children merge requirement?
Upvotes: 3
Views: 4809
Reputation: 1073
So the problem is caused by that the user groups list I prepared for the test is Unmodifiable
Upvotes: 6