3

I'm using SpringBoot, when a repository is called for the AModel, the repository is executing queries for BModel, CModel and DModel even when I am not calling for either CModel or DModel. any idea why this is happening and how I can prevent it?

@Entity
public class AModel extends Model {

  @OneToOne(fetch = FetchType.EAGER)
  @JsonIgnore
  private BModel;
}

@Entity
public class BModel extends Model {

  @OneToOne(fetch = FetchType.LAZY)
  private CModel;

  @OneToOne(fetch = FetchType.LAZY)
  private DModel;
}

 @Query("select a from com.project.models.AModel a where a.id = :id")
 @Override
 Candidate findOne(@Param("id")Long id);
Ricardo Mogg
  • 559
  • 6
  • 18

2 Answers2

1

The reason here is that when the entity AModel includes entity BModel, which in turn includes CModel and DModel. It has to fetch CModel and DModel when the fetch for AModel is called, otherwise your queries won't be able to complete if the objects of CModel and DModel are not fetched for, and the entire purpose of making the fetchType as Eager for AModel will be gone.

shruti1810
  • 3,487
  • 1
  • 14
  • 27
1

This happens cause of the oneToOne relations from BModel to CModel and DModel.

When you define a relation with FetchType.LAZY, then hibernate needs to substitute the object with a proxy, so that when you access this the first time, it can load it.

Now with oneToOne relation which is nullable, hibernate has no chance to know, if the relation is null or not without execute a select, cause the table in relation usually use the same primary key.

So if your relations are nonnullable, then define optional = false and no eager fetching is done. If this is not the case you could also use a oneToMany relation instead.

See also this stackoverflow question

Community
  • 1
  • 1
sfrutig
  • 277
  • 2
  • 12