I am trying to implement a unidirectional many to many relationship between 2 tables as follows:
@Entity
@Table(name="Book")
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="book_name")
private String bookName;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "book_author",
joinColumns = { @JoinColumn(name = "book_id") },
inverseJoinColumns = { @JoinColumn(name = "author_id") })
private List<Author> bookAuthors;
//getter and setters here
}
My author class is as follows:
@Entity
@Table(name="Author")
public class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="author_name")
private String authorName;
@Column(name="author_description")
private String authorDesc;
//getter setters here
}
The code for saving data is as follows (Note that I am invoking save on the book object which is the owning entity):
//create book
Book book1 = new Book();
book1.setBookName("Book1");
//create and set Author info
Author author1 = new Author();
author1.setAuthorName("a1");
author1.setAuthorDesc("a1 description");
Author author2 = new Author();
author2.setAuthorName("a2");
author2.setAuthorDesc("a2 description");
List<Author> authorsList1 = new ArrayList<Author>();
authorsList1.add(author1);
authorsList1.add(author2);
book1.setBookAuthors(authorsList1);
//save book
session.save(book1);
This executes the following hibernate code:
Hibernate: insert into Book (book_name, category_id, numOfCopies) values (?, ?, ?)
Hibernate: insert into Author (author_description, author_name) values (?, ?)
Hibernate: insert into Author (author_description, author_name) values (?, ?)
When I query the tables, I see data in the Book and Author table but not in the join table i.e. Book_author. Any idea what I could be doing wrong?
I referred to the following example: http://websystique.com/hibernate/hibernate-many-to-many-unidirectional-annotation-example/
I even tried changing the code to a bidirectional mapping by adding books into my author class as follows:
@ManyToMany(mappedBy="bookAuthors")
private List<Book> books;
but still no data gets saved into the join table.
Any help would be much appreciated!
Thanks in advance!