多对多关系不会将新实体添加到 table

Many to many relationship doesn't add new Entity into the table

我有两个实体 Book 和 BookTag。它们通过多对多关系连接。

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(name = "books")
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idbooks", insertable = false, updatable = false)
    private Long id;

   // other columns

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "books_tags",
            joinColumns = {@JoinColumn(name = "book_id")},
            inverseJoinColumns = {@JoinColumn(name = "book_tag_id")}
    )
    Set<BookTag> tags = new HashSet<>();

    // getters and setters
}

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
@Table(name = "book_tag")
public class BookTag {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", insertable = false, updatable = false)
    private Long id;

    // other columns
 
    @ManyToMany(mappedBy = "tags")
    private Set<Book> books = new HashSet<>();

    // getters and setters
}

我尝试使用这种服务方法向 bookTags 集合添加新的 BookTag 实体

    public void updateBook(Book book, String tag) {

        if (tag != null && !tag.equals("")) {
            BookTag bookTag = bookTagService.findBookTagByTagName(tag).orElse(new BookTag(tag));
            Set<BookTag> allTags = book.getTags();
            allTags.add(bookTag);
            book.setTags(allTags);
        }

        bookRepository.save(book);
    }

但它不起作用,在我将一个实体保存到 mysql 数据库后它可以正常工作 view of books_tags table after inserting a new tag to the book

在我尝试使用上面的方法向书中添加新标签后,我得到了这样的结果 view of books_tags table after adding a new tag to the book

如您所见,我的方法没有添加新实体,它为新的 bookTag ID 更改了现有条目。请帮我解决这个问题。

这一行实际上 return 一个未保存的图书标签: BookTag bookTag = bookTagService.findBookTagByTagName(tag).orElse(new BookTag(tag));

所以在将 bookTag 添加到完整的 Book 之前调用 save。