0

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.

Ian
  • 30,182
  • 19
  • 69
  • 107
Virkom
  • 373
  • 4
  • 22
  • Does it work to get the entire `List` for all articles in a single query, then organize them into the structure you need on the client side? That way you just have one (large) query. From your description, the backing model for the `TreeTableView` needs the entire list of data anyway. – James_D May 26 '16 at 14:34
  • Yes, I want a single query, then organize them into the structure on the client side. But now I have over 1000 queries to database for show list of products when my frame is loading. I mean, this is a bad decision. – Virkom May 26 '16 at 14:41

1 Answers1

2

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));
James_D
  • 201,275
  • 16
  • 291
  • 322