0

I am making a spring-boot project and currently I am facing a problem with lazy fetching. I have three classes one that is fetching its children with eager(Incident) and two that are with lazy(FileContent, FileStorage). The structure is:

Incident(1) -> (m)FileContent(1) -> (m)FileStorage.

Whenever I fetch from Incidet all of the fileContents and all of the fileStorages are also fetched. This should not be happening, fileStorages should not be fetched. It would be great if someone could tell me why the code behaves like this and help me fix It.

These are the classes:

@Getter
@Setter
@Entity
public class Incident extends BaseEntity {

    @JsonIgnore
    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "incident", orphanRemoval = true)
    private List<FileContent> fileContent;
}

@Entity
@Getter
@Setter
public class FileContent extends BaseEntity {

    @Column
    private String fileName;

    @OneToOne(mappedBy = "fileContent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private FileStorage fileStorage;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "incident_id")
    @LazyCollection(LazyCollectionOption.TRUE)
    private Incident incident;
}

@Getter
@Setter
@Entity
public class FileStorage extends BaseEntity {

    @Lob
    @Column
    private byte[] content;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "file_content_id")
    private FileContent fileContent;
}

@Service(value = "ins")
public class IncidentService {

    public Page<Incident> findAll(Pageable pageable) {
        Page<Incident> incidents = incidentRepository.findAll(pageable);

        if (CollectionUtils.isEmpty(incidents.getContent())) {
            return null;
        }

        return incidents;
    }
}

And this is the yml properties file

application.yml 
  - open-in-view: false

spring boot jpa java

1 Answers1

0

Changed @OneToOne(fetch = FetchType.LAZY), to @OneToOne(optional = false, fetch = FetchType.LAZY) and it worked fine.