I am trying to setup a Many-To-Many relationship using annotations.
here are my entities
Code:
@Entity
public class Publisher{
@Id
public int id;
public String name;
}
@Entity
public class PublisherBook{
@Id
public int id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="bookId",nullable=false)
public Book book;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="publisherId",nullable=false)
public Publisher Publisher;
}
@Entity
public class Book{
@Id
public int id;
public String name;
@OneToMany(fetch=FetchType.EAGER, mappedBy="book")
public Set<BookAuthor> authors;
}
@Entity
public class BookAuthor{
@Id
public int id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="bookId",nullable=false)
public Book book;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="authorId",nullable=false)
public Author author;
}
@Entity
public class Authors{
@Id
public int id;
public String name;
}
Here is the same data I have
Code:
Author:( id,name)
1, Author 1
2, Author 2
3, Author 3
Book: (id, name )
1, Book 1
2, Book 2
3, Book 3
Publisher(id,name)
1, Publisher 1
2, Publisher 2
3, Publisher 3
BookAuthor (id, bookId, authorId)
1, 1, 1
2, 1, 2
3, 1, 3
4, 2, 1
5, 3, 2
PublisherBook(id, publisherId, bookId)
1, 1, 1
2, 1, 2
3, 1, 3
4, 2, 1
5, 3, 2
If I try to get list of all books for Publisher 1 (id=1) from PublisherBook table, it should return total of 3 books.
But I am getting a total of 5 books. Book 1(id = 1) is being repeated 3 times with different author values (1, 2, 3)
So the list of PublisherBook returns
Code:
1, 1, 1
1, 1, 1
1, 1, 1
2, 1, 2
3, 1, 3
If I remove the Set<BookAuthor> from Book entity, the list of PublisherBook for publisher 1 returns the correct values
Code:
1, 1, 1
2, 1, 2
3, 1, 3
Can someone tell me what am I doing wrong?