0

I am 100% sure I did not fully explain my question in the title. My English wasn't enough to explain.

I have 2 Entities. User and Book. User has a list named readBooks. I want to reach the books in that list using HQL.

@Entity
public class Book {
 ... (nothing about users)
}
@Entity
public class User extends BaseUser {
    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private List<Book> readList;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    private List<Book> favoriteList;
}

I know I can easily reach the readList with user.getReadList(). However, I need to reach that list using HQL so that I can apply server-side pagination and sorting easily by just adding a Pagable to the function.

  • Are you looking for a [join](https://stackoverflow.com/a/1167969/10601203) in HQL? Also those fields in `User` are pulled down every single time you get a user, just because of the many-to-many join. They aren't lazy loading, they're eager loading. If you're worried about getting every single result, I would just get rid of that relationship altogether (from the code at least) and just manually query the user id from `Book` when you need the books. This way you can also use [limit and offset](https://stackoverflow.com/a/11655956/10601203) for server side pagination. – Jesse Aug 19 '22 at 23:14
  • Are you sure about the default fetch type of the ManyToMany annotation? I think it is set to LAZY default. Even so, I use Dto classes in queries, not the entities themselves, and these lists are not there. Therefore, I'm not fetching those fields every time. Still, thanks for the suggestion. – Umut Emre Önder Aug 19 '22 at 23:37

0 Answers0