Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: insert ManyToMany, generate ID in relationship table

Let I have Tables (Books and Authors have ManyToMany relation ship)

BOOKS
id
book_name

AUTHORS
id
author_name

BOOKS_AUTHORS
id
book_id
author_id

I map this Tables on Entities

class Books  
{  
   @Id  
   long id;  

  @Column(name = "author_name")
   String name;


   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "BOOKS_AUTHORS", 
              joinColumns = @JoinColumn(name = "book_id"),
              inverseJoinColumns = @JoinColumn(name = "author_id"))  
   List<Authots> authors;  

// setter, getters, adder  
}  

class Authors  
{  
   @Id  
   long id;  

   @Column(name = "author_name")
   String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "BOOKS_AUTHORS", 
              joinColumns = @JoinColumn(name = "author_id"),
              inverseJoinColumns = @JoinColumn(name = "book_id"))  
   List<Books> books;  

// setter, getters, adder  
}  

Now, I try do next

public void addAuthor(final String bookName, final Author author)
{  
      final Book book = // get book from database by bookName
      if (book == null)
         throw new DataNotFoundException("Book not found :(");
      author.addBook(book);
      book.addAuthor(author);  
      entityManager.persist(author);  
}  

1) I get exception that ID of BOOKS_AUTHORS record must be not NULL
2) How I can Generate ID (ising sequance generator) for relationship-table BOOKS_AUTHORS

like image 600
Ilya Avatar asked May 04 '12 09:05

Ilya


2 Answers

You cannot use @ManyToMany to create join table with id field in it.

If id field in the join table is a requirement, you have to create a special entity class (such as BookAuthor) for that table and connect it with books and authors with @ManyToOne/@OneToMany relationships.

Otherwise you need to remove id field from BOOKS_AUTHORS table.

like image 129
axtavt Avatar answered Oct 31 '22 15:10

axtavt


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

If books_authors is not mapped using Hibernate, then use the database side auto id incrementor. Example:

ALTER table book_authors CHANGE id long NOT NULL AUTO_INCREMENT;
like image 23
Bitmap Avatar answered Oct 31 '22 15:10

Bitmap