0

Using Hibernate 5.2 and Java 8 I have a table named PatientMetaData which has the followng fields (in the DB table itself, hmo is an integer):

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
private String name;
@ManyToOne
@JoinColumn(name="hmo")
private Hmo hmo;

The Hmo table contains a uid and a name:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int uid;
private String name;

and is related to the patients table through the uid in hmo table and hmo in patients table.

When loading all the patients, I see that for each patient, there is a query for its HMO.
However there 10K patients and only 7 HMOs, so it seems redundant to load the HMO for each patient.
I there a way to avoid all these queries?

One option is to define the PatientMetadata entity class to have the hmo as an integer so I will only load the patients, then load all the HMOs into a Java map, and finally I will grammatically attach an HMO from the map to each patient.

This looks a little cumbersome.
Is there a better way of doing so directly with Hibernate?

Guy Yafe
  • 991
  • 1
  • 8
  • 26

1 Answers1

2

Hibernate has curious behavior when using lazy fetch on a @ManyToOne, so this will probably not work.

I recommend using @BatchSize (2 possible positions, on Hmo class or on the relation in the patient).

Depending on how you retrieve your patients, you can also fetch Hmos via root.fetch() in JPA criteria queries, so that HMos get loaded with a left join.

The workaround is really a hack imo and should be avoided.

Kirinya
  • 245
  • 3
  • 12