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

跟風遠走 提交于 2019-12-12 02:13:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/41414874/jpa-onetomanyfetch-fetchtype-eager-pagination-and-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!