Home > Blockchain >  Spring Security Hibernate load user with lazy associations
Spring Security Hibernate load user with lazy associations

Time:08-16

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

CodePudding user response:

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.

CodePudding user response:

What's the problem with letting these associations just be lazy loaded when requested in code? You can always detach the entity from your entity manager first and then reload it with the fetch joins that you need, based on context. Something like:

User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
entityManager.detach(u);
u = entityManager.createQuery("from User u join fetch ... where u.id = :id")
    .setParameter("id", u.getId())
    .getResultList()
    .get(0);
// Work with u
  • Related