While using Spring Data JPA in an application, you typically define your entities (@Entity) and write a Repository Interface (which extends CrudRepository) and do some additional configuration which is out of scope for this question.
For example,
@Entity
public class Product {
// code removed for brevity
}
public interface ProductRepository extends CrudRepository<Product, Long> {
// code removed for brevity
}
Now if I’ve multiple entities like above and need to design a service API like searchByProductAndUserAndLocation (say all three are database tables), how should I be doing this in Spring data JPA? Assume that I write entity classes for Quantity/Cost as well. Obviously, I need to join the tables on some criteria (using foreign key), but I’m not clear on which repository should hold such queries as I feel that there is no specific owner repository/class here.
Also, I could expose the data by ProductService, LocationService and so on and then combine the results, but I wouldn’t be utilizing the database layer join or other optimizations eventually impacting the application performance.
I’m sure this is a very common use-case, what’s the general practice for this?
Thanks in advance.
I believe it’s reasonable to assign your method to the repository depending on the return type of the method, e.g.: