I have JavaFX
Application with TreeTableView
.
I want to show list of products in tree. First level of tree must contain Product.article. Second level of tree must have list of products contains Product.article, like this:
article1/
-- name model sizes
-- name model sizes
article2/
-- name model sizes
-- name model sizes
I have developed this with foreach on List<String article>
but database table on production will be contain over 1000 articles. Each article should have a list of products from database by distinct query. It will be so slow...
Is there any way to get result set of Hibernate query as Map<String article, List<Product>>
?
P.S.: Sorry for my bad English.
You can retrieve all the products as a List<Product>
in one query using
TypedQuery<Product> query = em.createQuery("select p from Product p", Product.class);
List<Product> allProducts = query.getResultList();
and then organize them:
Map<String, List<Product>> productsByArticle = allProducts.stream()
.collect(Collectors.groupingBy(Product::getArticle));
That should be reasonably efficient as it only involves a single query, and assuming you need all the data anyway, you need to get it somehow. The "grouping by" operation is more or less linear in the number of products (I think), and likely the time taken is negligible compared to executing the query.
(Obviously, you can do this in a single shot, though it's doing exactly the same thing):
TypedQuery<Product> query = em.createQuery("select p from Product p", Product.class);
Map<String, List<Product>> productsByArticle = query.getResultList().stream()
.collect(Collectors.groupingBy(Product::getArticle));