Home > Software engineering >  Child Entity is also getting queried with Lazy loading in OneToOne Mapping
Child Entity is also getting queried with Lazy loading in OneToOne Mapping

Time:06-10

I want to lazily load a @OneToOne Mapped child Entity. I am using SpringDataJPA version-2.6.7

@Entity
@Table(name = "a")
@Getter
@Setter
@NoArgsConstructor
@Slf4j
public final class A {

  @Id private Integer id; 

   @OneToOne(fetch = FetchType.LAZY)
  @MapsId
  @JoinColumn(name = "id", nullable = false)
  private B b;
  
}


@Entity
@Table(name = "b")
@Getter
@Setter
@NoArgsConstructor
public final class B {

  @Id
  private Integer id;

  @Column(name = "test_column")
  private String testColumn;
  
}

Here the Id of table 'A' and 'B' have shared primary key.

@Repository
public interface ARepository extends JpaRepository<A, Long> {
  Optional<A> findById(Integer id);
}

When Invoking

 @Autowired
    ARepository repo;
    
    void fetchData(){
        repo.findById(1);
    }

Query to fetch both A and B is getting fired. Can anyone please tell me what i am doing wrong?

CodePudding user response:

Try to also add optional = false:

@OneToOne(fetch = FetchType.LAZY, optional = false)
@MapsId
@JoinColumn(name = "id", nullable = false)
private B b;

CodePudding user response:

By default the fetch type is EAGER. You have to write :

@OneToOne(fetch=FetchType.LAZY)
  • Related