Home > Software engineering >  Spring Boot JPA -> Lazy Loading
Spring Boot JPA -> Lazy Loading

Time:01-03

I'm currently in the process of migrating an API built in Laravel/PHP to Spring Boot and had a question on best practice/how to approach the problem.

In laravel, I have a User model, with 3 child relationships: roles, communities and profiles. In laravel, I'd use Resources to dictate the data I'm returning in an API response, for example a GET /id would return the user with all of the child relationships, where as on a GET / list operation, it would return the base model with no child relationships.

What is the best way to replicate this with Spring Boot JPA? I had looked into Jackson JsonViews, however this only seems to reduce the object returned by the API, rather than limiting the amount of SQL queries being ran.

Any suggestions are appreciated. Thanks!

CodePudding user response:

If all of your relationships are Lazy (as they normally should be), then JsonViews is the right solution.

Whenever the joins are lazy, there is no query for the child data until the field has been accessed. So if the JsonView on / excludes the roles member of the User object, then the Json serializer will never call user.getRoles(), so the query is never run.

But if the JsonView for /id does include roles, then the serializer will have to call user.getRoles(), and at that time the query is run.

If you need even more optimization, then you can also attach an EntityGraph to a function on your repository like this:

public class UserRepository<User,Long> {

  @EntityGraph(attributePaths = {"roles", "communities", "profiles"})
  User getDetailedUserById(Long id);
}

This will force Eager loading for those otherwise lazy attributes, which means there will only be one query run.

  • Related