0

I am struggling trying to make a method to get an object from database and load the dependencies.

In normal case I never want to load it so my two objects look like this :

public class Training implements Serializable {

    [...]

    // Default => LAZY
    @OneToMany(mappedBy = "training")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Video> videoLists = new HashSet<>();

    [...]
}

public class Video implements Serializable {

    [...]

    // Default => EAGER
    @ManyToOne(optional = false)
    @NotNull
    @JsonIgnoreProperties("videos")
    private Training training;

    [...]
}

To achieve a certain goal I need to load my training in eager mode so I've made this function :

@Repository
public interface TrainingRepository extends JpaRepository<Training, Long> {

    @Query("from Training t left join fetch t.videoLists")
    List<Training> findEager();

}

This code make a StackOverflow error because of this cyclic fetching. What is the best way to keep my EAGER/LAZY fetching while making this function working ?

hamed
  • 7,939
  • 15
  • 60
  • 114
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41
  • Possible duplicate of [Infinite Recursion with Jackson JSON and Hibernate JPA issue](https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue) – Alan Hay Jun 05 '19 at 07:09

1 Answers1

1

In general, loading a collection along side with every record is not recommended. In your case, suppose each training has 100 or more videos, so you are loading 100 or more videos along side with each training. Also, you don't have any pagination mechanism in your relations, so you load all videos with each training. It can be a bottleneck in your application. I think you should change your design to overcome this problem rather than change eager/lazy configuration. For example, you can load just training without videos, and in your UI, when a user clicks on a training, loads videos of it.

But if you want to make that query working without any changes, I think probably using fetch = FetchType.LAZY in your ManyToOne can solve your stackoverflow problem.

hamed
  • 7,939
  • 15
  • 60
  • 114