Search code examples
spring-data-jpainner-joinspring-repositories

Which Spring Data repository to choose when you use an INNER JOIN or return attributes from several entities?


Working with Spring Data JPA repositories and with the methods annotated with @Query like the below one, I dont know if this query should be in the UserRepository or AddressRepository in this case. Its even more complicated when you want to return attributes from both entities. Thanks!

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u.name from User u JOIN u.address a where u.emailAddress = :emailAddress  and a.zipcode=:zipcode")
  User findByEmailAddressAndZipCode(String emailAddress, String zipcode);
}

Solution

  • It returns a User I'd therefore expect it to exist in the UserRepository. The User already knows about Address via the attribute of the same name, so it is ok for the UserRepository to do so as well.

    The fact that the User contains a reference to the Address is otherwise irrelevant for picking the right repository.

    If you have queries returning something completely different from User and Address, e.g. some statistics about the number of users per city, it could make sense to have a separate repository, either based on an entity mapped to a view or a complete custom implementation independent of Spring Data. That kind of entity and repository live in a different Bounded Context.

    Another question you should consider though is if you need/want a AddressRepository at all. We obviously hardly know your domain, but from what I see it seems likely that an Address does not exist independent from a User and therefore should be part of the User-Aggregate and not have its own repository. See https://stackoverflow.com/a/21277087/66686