1

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);
}
Renis1235
  • 377
  • 1
  • 13
user3254515
  • 1,255
  • 2
  • 17
  • 23
  • I would create a `Repository` that acts like an middle tier between both of them, maybe call it `UserAddressRepo` – Renis1235 Apr 13 '21 at 20:44

1 Answers1

1

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

Jens Schauder
  • 65,795
  • 24
  • 148
  • 294
  • Ok, understood, I was thinking in the example above but a little modified like the next one @Query("select a.zipCode from User u JOIN u.address a where u.emailAddress = :emailAddress ") String findZipCodeByEmailAddress(String emailAddress); – user3254515 Apr 14 '21 at 17:51