在hibernate中删除多对多

时间:2016-01-18 03:03:14

标签: hibernate many-to-many

我的pojos就像下一个:

@Entity
    @Table(name="author_mu")
    public class Author {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
        private String name;
        @ManyToMany(cascade={CascadeType.PERGE,CascadeType.MERGE})
        @JoinTable(name="author_book",joinColumns=@JoinColumn(name="author_id"),
                inverseJoinColumns=@JoinColumn(name="book_id"))
        private List<Book> books;

@Entity
@Table(name="book_mu")
public class Book {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @ManyToMany(cascade={CascadeType.PERGE,CascadeType.MERGE})
    @JoinTable(name="author_book",joinColumns=@JoinColumn(name="book_id"),
            inverseJoinColumns=@JoinColumn(name="author_id"))
    private List<Author> authors;

然后使用以下代码进行保存:

List<Author> authors = new ArrayList<Author>();
        List<Book> books = new ArrayList<Book>();
        List<Author> authors2 = new ArrayList<Author>();
        List<Book> books2 = new ArrayList<Book>();

        Author a1 = new Author();
        Author a2 = new Author();
        a1.setName("harry");
        a2.setName("gelin");
        authors.add(a1);
        authors.add(a2);
        authors2.add(a2);

        Book b1 = new Book();
        b1.setName("learn java in 30 days");
        Book b2 = new Book();
        b2.setName("stock market");     
        books.add(b1);
        books2.add(b1);
        books2.add(b2);

        a1.setBooks(books);
        a2.setBooks(books2);
        b1.setAuthors(authors);
        b2.setAuthors(authors2);

        s.save(a1);
        s.save(a2); 
        s.save(b1);
        s.save(b2);

然而,它在áuthor_book而不是3中保存了6条记录,即存在重复记录。 如果我只使用:s.save(a1); s.save(a2)或s.save(b1); s.save(b2), 那么错误:

  

org.hibernate.TransientObjectException:object引用未保存的瞬态实例 -   在刷新之前保存瞬态实例:com.my.hibernate.association.model.Book

发生。

那么,如何保存和删除多对多?

1 个答案:

答案 0 :(得分:1)

您需要在两个实体中定义映射,因此请尝试在作者中定义映射:

    @Entity
    @Table(name="author_mu")
    public class Author {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
        private String name;

        @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
        @JoinTable(name = "author_book",
        joinColumns = {@JoinColumn(name = "author_id")},
        inverseJoinColumns = @JoinColumn(name = "book_id"))
        private List<Book> books;

更多地参考这些:
Hibernate Bidirectional ManyToMany delete issue
http://outbottle.com/hibernate-manytomany-delete-non-owner-prevent-owner-being-deleted/