最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hibernate - Spring JPA attempts a DELETE operation when trying to Insert in @ElementCollection - Stack Overflow

programmeradmin5浏览0评论

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:

  1. Fetch all Tags
  2. Add new Tag
  3. Perform DELETE operation to remove all tags associated with user In DB
  4. 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.

发布评论

评论列表(0)

  1. 暂无评论