An object with an Eager fetch Type makes queries for the lazy loaded properties of that property .. why?

I am using SpringBoot, when the repository for AModel is called, the repository makes requests for BModel, CModel and DModel even if I do not call either CModel or DModel. any idea why this is happening and how can i 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);

      

+3


source to share


2 answers


The reason is that when an object AModel

includes an object BModel

, which in turn includes CModel

and DModel

. He must extract CModel

and DModel

, when called for a sample AModel

, or your request will not be able to perform if the objects CModel

and DModel

are not received, and all the goal of creating fetchType how Eager

to AModel

disappear.



+1


source


This is due to the oneToOne relationship from BModel to CModel to DModel.

When you define a relationship with FetchType.LAZY, then hibernate needs to inline a proxy object so that when it first accesses it, it can load it.

Now with the oneToOne relationship which is null, hibernate has no chance of knowing if the relationship is null or not without executing the select, the reason the table in the relationship usually uses the same primary key.



Thus, if your relationship is incurable, then define option = false and no forced fetch will be performed. If this is not the case, you can also use the oneToMany relationship.

See also this question fooobar.com/questions/37372 / ...

+1


source







All Articles