Search code examples
javaspring-boothibernatejpa

Conditional loading @ManyToMany JPA


I have a user Entity and Article Entity. The fetch type of articles is LAZY. I dont need to load articles all the time but I have a case in which I need to load the user favorites articles. How can I do it conditionally?

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
        name = "user_favorite_articles",
        joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "userId", nullable = false),
        inverseJoinColumns = @JoinColumn(name = "article_id", referencedColumnName = "articleId")
)
private List<Article> favoriteArticles;

Solution

  • 1. EntityGraph

    Optional<User> findById(Long id);
    

    2. JPQL or HQL

    @Query("SELECT u FROM User u JOIN FETCH u.favoriteArticles WHERE u.id = :id")
    Optional<User> findUserWithFavoriteArticles(@Param("id") Long id);