I have the following problem:
Setup:
- Two hierachical Entities (Element, DataElement), which contain an ElementCollection of Embeddables (Costs).
- The Embeddable from the ElementCollection has a OneToMany relationship to DataElement.
- Every relationship is eagerly fetched
Problem:
Sometimes! only on our server! I get a NullPointer exception, because an element is null which is! not null.
Example1:
Element.getChildren.get(0).getCosts().get(0).getDataElements().get(0).getLabel()
The getLabel() throws an NullPointer because the DataElement at index 0 is not yet present and thus null.
But if I run the exact same code with the exact same data again everything is fine.
The problem occures only on our server and not on our local machines (faster) even with the same db and application.
Sometimes it also happens while filtering Elements to only get those with a specific cost amount:
Element.getCosts().get(0).getAmount() > X
Could it be that despite being fetched eager the elements are yet not loaded from the db and thus are null?
Otherwise a cannot explain why sometimes alle data is present and sometimes some of the deeper ones are still missing.
Or maybe there is a problem with my data structure?
Super classes:
@MappedSuperclass @SequenceGenerator(name = "seq", initialValue = 1, allocationSize = 100) public abstract class BaseElement { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq") private Long id; etc... }
@MappedSuperclass public abstract class BaseCostElement extends BaseElement { @ElementCollection(fetch = FetchType.EAGER) private List<Cost> costs; etc... }
Hierarchical entities:
@Entity public class Element extends BaseCostElement { @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER) private List<Element> children; @ManyToOne private Element parent; etc... }
and:
@Entity public class DataElement extends BaseCostElement { @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER) private List<DataElement> children; @ManyToOne private DataElement parent; @Basic private String label; etc... }
Embedable:
@Embeddable public class Cost { @OneToMany(fetch = FetchType.EAGER) private List<DataElement> dataElements; @Basic private long amount; etc... }