Issue
I'm building a Spring Data JPA application and securing my API calls using Spring Security.
Principal is loaded through my custom implementation UserDetailsService.loadByUsername
(...)
, retrieving only the User
entity itself since all of its associations are LAZY by default.
This is done via a Spring Filter before each controller is hit (I'm doing JWT Auth)
For some requests (say POST /todo
), however, I will need to load some of the user's lazy associations (the user's Todos) as well in order to add new data to them and persist it.
Is there a suggested practice to achieve that?
My goal is to have some of those associations already loaded (depending on context) when getting the principal through SecurityContextHolder.getContext().getAuthentication().getPrincipal()
without necessarily setting them to EAGER.
Something along the lines of overriding the
UserDetailsService.loadByUsername
to JOIN FETCH the associations on demand when I need them.
Thanks
Solution
You don't need to load @ManyToOne
(like Todos) part of the associations at all.
Just create new TodoEntity
, assign a user to it and save.
if you need to modify anything, better to work with all the user's associations separately from a user.
Answered By - v.ladynev
Answer Checked By - Willingham (JavaFixing Volunteer)