I am trying to setup a Many-To-Many relationship using annotations. here are my entities
@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 a sample set of data that I have for the entities
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, book开发者_JS百科Id)
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
1, 1, 1
1, 1, 1
1, 1, 1
2, 1, 2
3, 1, 3
If I remove the Set from Book entity, the list of PublisherBook for publisher 1 returns the correct values
1, 1, 1
2, 1, 2
3, 1, 3
Can someone tell me what am I doing wrong? Apologies for the long post.
This is an effect due to the loading strategy of hibernate. You defined the relation "authors" as EAGER fetching, which will result in a JOIN of table AUTHOR.
So avoid this you can either define this relation as LAZY (which may have other positive or negative effects on your application) or use a result transformer:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
精彩评论