0 Replies Latest reply on Jul 15, 2005 11:08 AM by Didi

    working-with-@ManyToMany-relationship question

    Didi Newbie

      Hi!

      I have a BookBean with a @ManyToMany relationship to a AuthorBean (entity beans)

      in BookBean:
      private Collection author;

      @ManyToMany(fetch=FetchType.EAGER)
      @JoinColumn(name="Author_ID")
      public Collection getAuthor() { return this.author; }
      public void setAuthor(Collection author) { this.author = author; }



      and in AuthorBean:
      private Collection books;

      @ManyToMany(fetch=FetchType.EAGER)
      @JoinColumn(name="Book_ID")
      public Collection getBooks() { return this.books; }
      public void setBooks(Collection books) { this.books = books; }

      I read the statement (I think it was from Bill Burke) that CMR in EJB 3.0 is totally different
      from EJB 2.x and that you have to fill the collections as you would have done with regular
      POJOs. Another statement I read was that the Many side "owns" the relationship. With these
      two statements I created the following addAuthor method:


       public int addAuthor(String firstname, String lastname, int[] liste) {
       AuthorEntityBean author = new AuthorEntityBean(firstname, lastname);
       Collection<BookEntityBean> books = new ArrayList<BookEntityBean>();
       for (int i = 0; i < liste.length; ++i) {
       BookEntityBean be = em.find(BuchEntityBean.class, Integer.valueOf(liste\[i\]));
      // be.getAuthors().add(author);
       books.add(be);
       }
       author.setBooks(books);
       em.persist(author);
       return author.getId();
       }
      



      This adds the books to the authors but the authors are not automatically added to the books
      (a look in the database confirmed that). Inserting the commented line unfortunately did not
      solve this problem: then too many books and authors are added (even though I do not know
      why).

      Since I do not know what is wrong I ask you guys for help: how to add new items to a
      bi-directional relationship? And also important: how to remove items from such a relationship?

      Thanks in advance!



      PS: JBoss4.0.3RC1 with java 1.5.0_01-b08

      PPS: I had CMRs perfectly working with EJB 2.1