I am trying to improve the n + 1 query in a project that I am working on. I use Hibernate with the model shown below, and I want to request all the items related to the portfolio, including the last two prices for each product (the price for this date and previous price).

API Example:
List<Items> items = findItemsWithLatestTwoPrices(portfolio, latestPriceDate);
Currently, I use one query to retrieve all the items associated with the portfolio, and then iterate over these items to request the last two prices for this item (so n + 1).
I tried to express this in my native sql using a correlated subquery, but the performance was terrible. This and the fact that there are new prices every day (so the request becomes slower) made me think that I need a different model, but Im struggling to create a model that is reasonably efficient and constant over time, as the amount of growth prices.
I was thinking of different solutions, including representing prices as linked lists or using some kind of tree, but I think there are better alternatives. Am I missing something? Has anyone working on a similar problem come up with a good solution?
I donโt care if I use HQL or my own SQL, while the performance is decent. I am also open to making changes to the model.
Thanks!
[change]
Since I have more than two years of pricing data, and there may be more than 1000 pr items. portfolio, extracting the entire schedule is probably not a good idea. I also need random access by date, so saving two prices as the fields in the element, unfortunately, are not an option.
ebaxt source share