I would like to know how to best use Spring Data to query the same set of database tables differently depending on the use cases.
Scenario: Products can be bought by Users via Orders. Each Product can either be a standalone product or consist of multiple Subproducts (self referencing table).
The database schema is managed separately.
What’s the most elegant way to retrieve different models from the same set of tables using Spring Data? Considering the following queries:
- Get all products including their subproducts
- Get all the users that purchased a product
- Get all products with the number of purchases for each.
From a framework agnostic view I would create separate models for each and then fill them with the result of an sql query. This would lead to
- A CombiProduct entity that maintains references to other CombiProducts.
- A UserProduct that maintains references to all users that bought it.
- A PurchasedProduct that maintains a purchase count. Each model would be different, because the use case that needs the UserProduct doesn't need information about sub products for example. The use case would then define what's needed from the database.
But with Spring Data i can't find any easy-to-use solutions for scenarios like this. Because the whole Repository support in spring-data-jdbc requires me to define AggregateRoots. And with Aggregate Roots it seems like I can only ever have a table/entity in a single Aggregate (and not have three separate ones like described above) - Am I right?
And the other possibility is querying the database using JdbcTemplate which looks like it could end up beeing a lot of boilerplate code.
What is the spring-data way of creating solutions like that?