I have the following entity:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@ElementCollection
@CollectionTable(
name = "user_tags",
joinColumns = @JoinColumn(name = "user_id")
)
@Column(name = "tag")
private Set<String> tags = new HashSet<>();
}
And the following function:
@Transactional
public User addTagToUser(Long userId, String tag) {
User user = userRepository.findById(userId).orElseThrow(() -> new
RuntimeException("User not found"));
List<String> tags = user.getTags();
tags.add(tag); // Add a new tag
return userRepository.save(user); // Save the updated user
}
When the above function is invoked, Spring JPA does the following:
- Fetch all Tags
- Add new Tag
- Perform DELETE operation to remove all tags associated with user In DB
- INSERT the list created in Step 2.
Is there a way to instruct JPA to not do the DELETE operation and do a simple insert? Providing DELETE grant to a DB account is not good practice as far as I understand.