JPA/Hibernate @OneToMany collections incompletely populated

Yesterday I tracked down a strange bug in our entity classes, which are based on JPA and are used in an environment with Hibernate as persistence provider.

I had some very basic classes that looked something like the following:

public class TheWhole extends BaseEntity {
  @OneToMany(mappedBy = "theWhole", fetch = FetchType.EAGER)
  private List<Part> parts;
  List<Part> getParts() { return parts;}

public class Part extends BaseEntity {
  private TheWhole theWhole;

As simple as it can be, shouldn’t be any problems there!

However, when fetching the list of parts by callling TheWhole.getParts() it was incompletely populated. I could see that the database contained ~250 rows, but when checking in the debugger, there was only 60 items in the collection.

I checked all annotations and DDL but could not find any problems there. I also tried by iterating the collection (in case the eager fetching did not work correctly), but with no success . I finally tried a workaround with a named query of the form:

  name = "Part.findByTheWhole", 
  query = "select p from Part p "+
          "where p.theWhole = :theWhole")

and then everything worked fine and all 250 items where fetched. Since this more or less is the query that a one-to-many fetch boils down to, the getter ought to work as well.

After some digging around, I got a clue when reading that equals/hashcode is used when Hibernate populates the collection.

I checked the classes again, but the classes themselves did not override the methods. However, the base class BaseEntity did, and it was doing it wrongly. This resulted in many objects where considered to be the same. After having corrected the equals/hashcode in the base class everything worked fine.

So, in the case that one-to-many relationships seem to be incorrectly (partially) populated, check if the equals/hashcode methods are overridden and that the implementations are correct.

IT consultant and Java specialist at CAG Contactor.

Publicerad i Uncategorized
2 comments on “JPA/Hibernate @OneToMany collections incompletely populated
  1. Andreas Brodow skriver:

    Trodde först att det berodde på att alla inte ville visa upp sina ”private parts” 🙂


WP to LinkedIn Auto Publish Powered By :