更新 Hibernate ManyToMany 关系中的现有记录

Update existing records in Hibernate ManyToMany Relation

在我的数据库中我有两个 tables BookLabel 以及 ManyToMany 他们之间的关系。我已经使用 ManyToManyCascadeALL.

的注释在 Hibernate 中成功映射了它们

现在考虑这种情况。

当我添加带有标签列表的新书时。标签列表包含现有标签和新标签。当这本书保存在数据库中时,它会创建现有标签的重复条目。 [意味着每次都会使用不同的主键创建一个新标签(即使是现有标签),而不是使用现有和更新 ManyToMany Table] 的引用。我想要休眠以更新现有标签并创建新标签。类似地,ManyToMany table 会自行更新。

我可以想到手动解决方案。

但我相信这是解决方案,涉及很少的冗长编码和不必要的处理,并且可以改进。

Hibernate 是否提供了一些内置功能来解决这个问题以及如何改进我的解决方案。

这是我的图书实体

@Entity
@XmlRootElement
public class Book {
@Id
@GeneratedValue
private int bookID;
private String bookName;
private String bookDescription;
private String bookAuthor;
private String bookEdition;
private String bookDownloadURL;
private String bookImageURL;

@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "book_label", joinColumns = { @JoinColumn(name = "books_bookID") }, inverseJoinColumns = {
        @JoinColumn(name = "labels_labelID") })
private List<Label> labels = new ArrayList<Label>();
//getters and setters

标签实体

@Entity
@XmlRootElement
public class Label {

@Id
@GeneratedValue
private int labelID;
private String labelName;
private String labelDesc;
@ManyToMany(mappedBy="labels",fetch=FetchType.EAGER)
private List<Book> books = new ArrayList<Book>();
// getter and setters

在我的数据库中,我已经创建了三个 table

  1. book table col 名称与 Book 实体的数据成员完全相同
  2. label table 的 col 名称与 Label 实体的数据成员完全相同
  3. book_label table 有两列 books_bookID、labels_labelID。这些列分别从其他两个表中引用 bookID 和 labelID(意味着它们实际上是外键)

这是我的测试用例代码

    BookDAO booksDao = new BookDAO();
    LabelDAO labelDao = new LabelDAO();

    //Label by these name exist already in database. 
    //Upon adding the new book it should use the previous label and do entries in manytomany table accordingly
    // (shouldn't create new labels with same names and map against them) <- THis is happening now 

    Label label1= new Label();
    label1.setLabelName("Fantasy");

    Label label2= new Label();
    label2.setLabelName("Literature");


    Book book1= new Book();
    book1.setBookName("Talaash");
    book1.getLabels().add(label1);
    book1.getLabels().add(label2);

    booksDao.addBook(book1);

如果我理解正确,你的问题是两个表都是关系的所有者,所以这会导致重复条目。只有一个 class 应该是关系的所有者。在其中一个 class 中尝试类似的操作:

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "books")
public List<Label> getLabels()

并且在您的标签中您应该有图书清单。 同样,如果我理解正确的话,因为您没有提供 classes 以便我们进行更好的分析