Hibernate Lazy fetching and Nested Models - CDCgov/prime-simplereport GitHub Wiki

SimpleReport uses the Hibernate ORM. When working with nested models you might find the situation that the object has only been partially instantiated. For example, when retrieving a TextMessageSent object you will notice that the PatientLink reference will display as null even though a record does exist in the patient_link table for the TextMessageSent instance. This normally happens because the model has been configured to fetch in Lazy mode @ManyToOne(optional = true, fetch = FetchType.LAZY). Lazy fetching tells hibernate to only retrieve the information of the table that matches the model and to not perform joins to retrieve the information needed to populated the nested models.

If you need to enable the fetching of records across multiple tables so the nested objects get fully populated then you will need to add a @EntityGraph annotation to the method that is performing that specific fetch in in the repo class.

Example

For example, to enable fetching if we would like to get the TextMessageSent instances fully populated when using the method findByTwilioMessageId the @EntityGraph annotation would look like this.

​​public interface TextMessageSentRepository extends AuditedEntityRepository<TextMessageSent> {

@EntityGraph(attributePaths = {"patientLink.testOrder.patient.phoneNumbers"})

TextMessageSent findByTwilioMessageId(String id);

}

Where patientLink.testOrder.patient.phoneNumbers is the chain of nested objects we want to receive populated. This will enable eager fetching just for this method.