Você está na página 1de 7

22/08/2017 Vaadin DataProvider Example - Vaadin Help

Vaadin DataProvider Example


Posted on May 3, 2017 by Vikrant Thakur

Previously Vaadin developers used a lot of proprietary interfaces called Containers, Items and Properties
to do the databinding. The old Container interface has been removed from the new Vaadin 8 API
altogether. See the Data API & other comparisons here. What is of utmost importance & interest is the
API to lazy load data from backend. See the official reference here. Lets understand the new API in the
following Vaadin DataProvider Example.

We will create our own concrete DataProvider class by extending AbstractBackEndDataProvider. See the


source code here:

1. public class EmployeeDataProvider extends AbstractBackEndDataProvider<Employee, String>


{
2.
3. private static final long serialVersionUID = 1L;
4.
5. private final EmployeeService employeeService;
6.
7. public EmployeeDataProvider(EmployeeService employeeService) {
8. // TODO Auto-generated constructor stub
9. this.employeeService = employeeService;
10. }
11.
12. @Override
13. protected Stream<Employee> fetchFromBackEnd(Query<Employee, String> query) {
14. // TODO Auto-generated method stub
15. return employeeService.fetchEmployees(query.getFilter().orElse(null),
query.getLimit(), query.getOffset(),
16. query.getSortOrders()).stream();
17. }
18.
19. @Override

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 1/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

20. protected int sizeInBackEnd(Query<Employee, String> query) {


21. // TODO Auto-generated method stub
22. return employeeService.countEmployees(query.getFilter().orElse(null));
23. }
24.
25. @Override
26. public Object getId(Employee item) {
27. // TODO Auto-generated method stub
28. return item.getId();
29. }
30. }

You will notice that this DataProvider has three key overridden methods:

1. fetchFromBackend()
2. sizeInBackend()
3. getId()
fetchFromBackend(): Whenever a Vaadin 8 list data component (Grid, ComboBox etc.) needs data, it
requests the needed data from the attached DataProvider. The component passes a Query object to
the DataProvider. The Query object contains important information like filter string (for fetching a filtered
resultset), limit & offset (to fetch the desired subset or page of the resultset).

sizeInBackend(): The Vaadin 8 list data components (Grid, ComboBox etc.) call fetchFromBackend() in


tandem with sizeInBackend() . The two methods must return the same information. To quote the official
text:

“The results of the first and second callback must be symmetric so that fetching all available items using
the first callback returns the number of items indicated by the second callback. Thus if you impose any
restrictions on e.g. a database query in the first callback, you must also add the same restrictions for the
second callback.”

getId(): This method returns the unique ID of the data objects. generally, this is usually the id property of
the the entity class. This getId() method helps the list data components (Grid, ComboBox etc.) to swap
out the stale objects from & swap in the fresh objects into their internal objects-cache.

Our EmployeeDataProvider above invokes the EmployeeService to fetch the desired data


(actual Employee records, as well as the count of records). Here is the source code:

1. public class EmployeeService {


2.
3. public static final String SORT_ON_ID = "id";
4. public static final String SORT_ON_NAME = "name";
5.
6. ArrayList<Employee> fetchEmployees(String filter, int limit, int offset,
List<QuerySortOrder> sortOrders) {
7. if (filter == null) {
8. filter = "";
9. }
10. filter = "%" + filter.toLowerCase().trim() + "%";
11.
12. if (sortOrders == null || sortOrders.isEmpty()) {
13. sortOrders = new ArrayList<>();
14. sortOrders.add(new QuerySortOrder(SORT_ON_NAME, SortDirection.ASCENDING));
15. }
16.
17. ArrayList<Employee> employees = new ArrayList<>();
18. Connection conn;
19. try {

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 2/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

20. conn = DatabaseService.getInstance().getConnection();


21. PreparedStatement stmt = conn.prepareStatement("select * from employee" + " where
lower(name) like ? "
22. + SortStringGenerator.generate(sortOrders) + " limit ? offset ?");
23.
24. stmt.setString(1, filter);
25. stmt.setInt(2, limit);
26. stmt.setInt(3, offset);
27.
28. ResultSet rs = stmt.executeQuery();
29.
30. while (rs.next()) {
31. Employee employee = new Employee(rs.getInt("id"), rs.getString("name"));
32. employees.add(employee);
33. }
34. conn.close();
35. } catch (SQLException e) {
36. // TODO Auto-generated catch block
37. System.out.println(e.getMessage());
38. } catch (IOException e) {
39. // TODO Auto-generated catch block
40. System.out.println(e.getMessage());
41. }
42.
43. return employees;
44. }
45.
46. int countEmployees(String filter) {
47. if (filter == null) {
48. filter = "";
49. }
50. filter = "%" + filter.toLowerCase().trim() + "%";
51.
52. int count = 0;
53. Connection conn;
54. try {
55. conn = DatabaseService.getInstance().getConnection();
56. PreparedStatement stmt = conn
57. .prepareStatement("select count(*) from employee" + " where lower(name) like ?
");
58.
59. stmt.setString(1, filter);
60. ResultSet rs = stmt.executeQuery();
61.
62. while (rs.next()) {
63. count = rs.getInt(1);
64. }
65. conn.close();
66. } catch (SQLException e) {
67. // TODO Auto-generated catch block
68. System.out.println(e.getMessage());
69. } catch (IOException e) {
70. // TODO Auto-generated catch block
71. System.out.println(e.getMessage());
72. }
73.
74. return count;
75. }

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 3/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

76. }

This EmployeeService makes use of H2 as the backend database. See the earlier post for Vaadin
Database Connection example. Our example-db.mv.db is located at “D:\data-provider-example”. See
attached screen-shot: 

Here is the source code for DatabaseService.java

1. public class DatabaseService {


2.
3. private static DatabaseService databaseService;
4. private JdbcConnectionPool connPool;
5.
6. private DatabaseService() throws IOException {
7.
8. // initialize a connection pool for H2
9. connPool = JdbcConnectionPool.create("jdbc:h2:tcp://localhost/d:/data-provider-
example/example-db", "sa",
10. "pass");
11. System.out.println("DatabaseService instantiated...");
12. }
13.
14. public static DatabaseService getInstance() throws IOException {
15. if (databaseService == null) {
16. databaseService = new DatabaseService();
17. }
18. return databaseService;
19. }
20.
21. public Connection getConnection() throws SQLException {
22. return connPool.getConnection();
23. }
24. }

Here is the source code for Employee.java

1. public class Employee {


2. private final int id;
3. private final String name;
4.
5. public Employee(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9.
10. public int getId() {
11. return id;
12. }
13.

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 4/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

14. public String getName() {


15. return name;
16. }
17. }

Here is the source code for SortStringGenerator.java. This class helps in converting the sorting
information, passed on by the list data components, into a format that can be used in our SQL queries.

1. public class SortStringGenerator {


2.
3. public static String generate(List<QuerySortOrder> sortOrders) {
4. String sortString = "";
5. int i = 0;
6. if (sortOrders != null && !sortOrders.isEmpty()) {
7. for (QuerySortOrder sortOrder : sortOrders) {
8. String order = getOrder(sortOrder.getDirection());
9. if (i == 0) {
10. sortString = "order by lower(" + sortOrder.getSorted() + ") " + order;
11. } else {
12. sortString = sortString + ", lower(" + sortOrder.getSorted() + ") " + order;
13. }
14. }
15. }
16. return sortString;
17. }
18.
19. private static String getOrder(SortDirection sortDirection) {
20. String order = "asc";
21. if (sortDirection == SortDirection.DESCENDING) {
22. order = "desc";
23. }
24. return order;
25. }
26. }

And, here is the source code for the UI:

1. @Theme("mytheme")
2. public class MyUI extends UI {
3.
4. /**
5. *
6. */
7. private static final long serialVersionUID = 1L;
8.
9. @Override
10. protected void init(VaadinRequest vaadinRequest) {
11. // create and initialize connection pool
12. final HorizontalLayout root = new HorizontalLayout();
13. root.setSizeFull();
14. root.setSpacing(true);
15. root.setMargin(true);
16. setContent(root);
17.
18. EmployeeService employeeService = new EmployeeService();
19. EmployeeDataProvider employeeDataProvider = new
EmployeeDataProvider(employeeService);
http://vaadinhelp.co.in/vaadin-dataprovider-example/ 5/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

20.
21. //combo-box
22. ComboBox<Employee> employeeCombo = new ComboBox<>("Employee Combo");
23. employeeCombo.setPlaceholder("Select employee...");
24. employeeCombo.setWidth("400px");
25. employeeCombo.setItemCaptionGenerator(emp -> {
26. return "#" + emp.getId() + " - " + emp.getName();
27. });
28. employeeCombo.setDataProvider(employeeDataProvider);
29.
30. //grid
31. Grid<Employee> employeeGrid = new Grid<>("Employee Grid");
32. employeeGrid.setWidth("400px");
33. employeeGrid.addColumn(emp->{return
"#"+emp.getId();}).setCaption("Id").setWidth(80).setSortProperty(EmployeeService.SORT_ON
_ID);
34. employeeGrid.addColumn(emp->{return
emp.getName();}).setCaption("Name").setWidth(320).setSortProperty(EmployeeService.SORT_O
N_NAME);
35. employeeGrid.setDataProvider(employeeDataProvider);
36.
37. //add components
38. root.addComponents(employeeCombo, employeeGrid);
39. }
40.
41. @WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
42. @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
43. public static class MyUIServlet extends VaadinServlet {
44.
45. private static final long serialVersionUID = 1L;
46. }
47. }

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 6/7
22/08/2017 Vaadin DataProvider Example - Vaadin Help

http://vaadinhelp.co.in/vaadin-dataprovider-example/ 7/7

Você também pode gostar