3
votes

I have a Class A which has one-to-many relationship with class B & C. I had set the fetchType to EAGER which causes the multiple bag fetch problem in JPA. Now there are two ways to solve the problem which I know of. Either I keep the fetch type Eager & change them from List to Set which is OK in my case, or change fetchType to "lazy" and use join query to EAGER fetch the relationships. What is the recommended approach?

4

4 Answers

3
votes

"multiple bag fetch problem in JPA"

Note that their is no "multiple bag fetch problem in JPA", this is a specific issue with Hibernate. Other JPA providers do not have this issue, and JPA fully allows you to have multiple EAGER OneToMany relationships.

1
votes

I'd prefer to fetch the collection (though the limit of a single fetch exists in queries aswell if you use hibernate), since changes are that you sometimes wish to list all A objects without wanting B & C. Personally I mostly use Lists since I want to show the collections directly into jsf datatables (which can't handle sets), and I'm forced to initialize collections by manually reading them in the backend rather than fetching them if it's more than a single collection.

1
votes

On eager collection fetch, Hibernate "cross-joins" your root and collection tables by default. This may lead to duplicate root elements being returned, which you may not want. Three possible solutions:

  1. don't eager fetch;
  2. force a select fetch (still eager but without the join fetch) using FetchMode.SELECT; or
  3. hash the results into a Set. Set approach recommended, provided you absolutely need always to have said collection attached. Peformance of a join fetch is better than select fetch even with the extra hashing step, which costs practically nothing.
0
votes

Consider mapping the collection as a list rather than bag. This is done by just adding the @org.hibernate.annotations.IndexColumn or, since JPA 2.0, prefer @javax.persistence.OrderColumn