0
votes

I need to get a entity and its collection from a Rest controler but I have a very strange behaviour with spring data JPA.

I have a ManyToMany relation beetween to entities with a Lazy loading.

@Entity
class Folder{
    ...
    @ManyToMany(fetch = FetchType.LAZY)
    protected Set<Tag> tags;

    ...getter setter
}

@Entity class Tag{

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "tags"
    protected List<File> files; 
}

And a JPQL query in a spring jpa repository

@Query("SELECT f FROM Folder f INNER JOIN f.tags t WHERE
        f.id = :id")
Folder findFolderById(@Param("id") int id);

So the Folder is supposed to be populated with the Tag collection and avoid the lazy loading part.

But I can see in the logs that after the Join Query there is a select on the Tag table, so a lazy loading.

Hibernate: select folder0_.id as id2_2_... Hibernate: select tags0_.files_id ...

I don't want to use fetch type EAGER because I don't always need the Tag collection. How can I avoid that Lazy loading ?

1
thank you next time I'll RTFM - Kaizokun
@AlanHay and Kaizokun: I read the linked doku, but I can't understand the use case in oracles example - JimHawkins
@JimHawkins : what don't u understand exactly ? - Kaizokun
what I read in oracles example is this: the query returns 5 references to the mag azinewith id 1 . Why is this useful? - JimHawkins

1 Answers

0
votes

Thanks to Alan Hay. The solution is simple we just need to use the Fetch keyword. In order to populate the collection.

@Query("SELECT f FROM Folder f LEFT JOIN FETCH f.tags t WHERE
        f.id = :id")
Folder findFolderById(@Param("id") int id);