Skip to content
Advertisement

JPA: @OneToMany(fetch = FetchType.EAGER), pagination and duplicates

I use eclipselink as a JPA provider. I have an entity Article which has many Authors (this field is marked @OneToMany(fetch = FetchType.EAGER)). Article and authors are loaded together using only one sql query (JOIN).

To work with pagination I use the following code:

String queryString="SELECT DISTINCT e FROM Article e LEFT JOIN FETCH e.authors";
Query query = em.createQuery(queryString);
query.setHint("eclipselink.join-fetch", "e.authors"); 
query.setFirstResult(position);
query.setMaxResults(amount);

When setFirstResult and setMaxResults are used they, as I understand, define limit part in sql query. As a result I have two problems:

  1. When I want to get 10 articles I get only two articles where the first article has 4 authors, and the second one has 6 authors
  2. Article duplication – I have one article with different authors on different pages.

How to solve such problem?

Advertisement

Answer

FirstResult and and MaxResult do not work as you would expect when using fetch JOINs over collections as they are database SQL performance operations as described here.

Don’t use a fetch join over a collection mapping if you need absolute pagination results – use batch fetching instead. This will use 2 queries, allowing the first to correctly return the required rows with pagination, and the second to return the rows required for the collection relationship. Specify the IN or batch.type be used to limit the secondary query.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement