user(m:m)books
@Entity
public class User{
@Id
public int id;
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Book.class)
@JoinTable(name = "user_book", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "book_id"))
@Fetch(FetchMode.SUBSELECT)
public List<Book> books;
}
@Entity
public class Book{
@Id
public int id;
...
}
loadAllActiveUsers()
foreach user
do(user.books)
假设我们有1000个用户,每个用户都拥有所有书籍(我们有1000本书)。 当调用user.books时,hibernate会触发查询:
select book.* from association inner join books b on b.id = association.book_id where association.user_id in (select u.id from users u)
此查询将包含1M行的结果,尽管我们有1000本书。 这是因为hibernate由user_id而不是book_id加载。
如果hibernate将在where子句中进行关联的连接,那么结果将限制为不同的书籍,我们将不会查询重复的书籍。
select book.* from books where b.id in (select association.book_id from users u join association a on a.user_id = u.id)
有没有办法告诉hibernate以2个步骤进行子选择:获取关联的id而不是获取关联的实体?