Loading...
Important Notice - Forums is archived

To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Product icon
TUTORIAL

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.

How to bind SQL resultset to vaadin grid

zakir syed
5 years ago Apr 01, 2017 7:54pm
Tatu Lund
5 years ago Apr 03, 2017 9:28am
ali akbar shahriari garaei
1 year ago Jul 28, 2020 8:11am
Jean-Christophe Gueriaud
1 year ago Jul 29, 2020 6:52am

You can do this:


        // Create the grid and set its items
        Grid<HashMap<String, Object>> grid2 = new Grid<>();
        grid2.setItems(rows); // rows is the result of retrieveRows

        // Add the columns based on the first row
        HashMap<String, Object> s = rows.get(0);
        for (Map.Entry<String, Object> entry : s.entrySet()) {
            grid2.addColumn(h -> h.get(entry.getKey().toString())).setHeader(entry.getKey());
        }

        // Add the grid to the page
        layout.add(grid2);

You have to deal with the conversion of your object (in my code it's done with toString() but I'm not checking if it's null or if it's a date ...).

Here the original solution for Vaadin 8: https://vaadin.com/forum/thread/16038356/grid-8-without-bean-class

ali akbar shahriari garaei
1 year ago Jul 29, 2020 9:16am
Jean-Christophe Gueriaud
1 year ago Jul 29, 2020 11:49am

Something like this should work.

  private Grid<Map<String, Object>> grid2 ;
  
   private void updateContent(String query) {
        List<Map<String, Object>> rows = null;
        try {
            rows = queryViewService.retrieveRows(query);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // Create the grid and set its items
		if (grid2 != null) {
		  remove(grid2);
		}
        grid2 = new Grid<>();
        grid2.setItems(rows); // rows is the result of retrieveRows

        // Add the columns based on the first row
        Map<String, Object> s = rows.get(0);
        for (Map.Entry<String, Object> entry : s.entrySet()) {
            grid2.addColumn(h -> h.get(entry.getKey())).setHeader(entry.getKey());
        }

        // Add the grid to the page
        add(grid2);
    }

If the columns are always the same you can also just run grid2.setItems(rows)