Connecting the View to the Backend

In the previous chapter, you created the view using Vaadin components and layouts. In this chapter, you will connect the view to the backend to display and update data.

You can find the backend code in the src/main/java directory.

This chapter covers:

  • Spring Boot.

  • How to create a Spring Service for interfacing the backend.

  • How to access a service from the view.

An Introduction to Spring Boot

Vaadin starter projects use Spring Boot on the server, although you can use Vaadin also without it. Spring Boot is an opinionated, convention-over-configuration approach to creating Spring applications. Spring Boot automates much of the required configuration and manages an embedded Tomcat server, so you don’t need to deploy the application to a separate server.

In this tutorial, you use the following features that are configured by Spring Boot:

  • Spring Data for accessing the database through JPA and Hibernate.

  • An embedded H2 Database for development, and PostgreSQL for production.

  • Spring Boot DevTools for automatic code reload.

  • Embedded Tomcat server for deployment.

  • Spring Security for authenticating users.

Backend Overview

The starter you downloaded contains the entities and repositories you need, along with a sample data generator.

Domain Model: Entities

The Vaadin CRM application has three JPA entities that make up its domain model: Contact, Company, and Status. A contact belongs to a company and has a status.

You can find the entities in the com.example.application.data.entity package.

Entity model diagram

Database Access: Repositories

The application uses Spring Data JPA repositories for database access. Spring Data provides implementations of basic create, read, update, and delete (CRUD) database operations when you extend from the JpaRepository interface.

You can find the repositories in the com.example.application.data.repository package.

Sample Data Generator

The com.example.application.data.generator package contains a sample data generator that populates the database with data. It uses CommandLineRunner, which Spring Boot runs when the application starts up.

Creating a Service for Accessing the Database

Instead of accessing the database directly from the view, you will create a Spring Service. The service class handles the application’s business logic and, in larger applications, it will often transform database entities into data-transfer objects (DTO) for views. In this tutorial, you will create a single service that provides all the methods you need.

Create a new class, CrmService.java, in the data.service package with the following content:

CrmService.java

  1. package com.example.application.data.service;
  2. import com.example.application.data.entity.Company;
  3. import com.example.application.data.entity.Contact;
  4. import com.example.application.data.entity.Status;
  5. import com.example.application.data.repository.CompanyRepository;
  6. import com.example.application.data.repository.ContactRepository;
  7. import com.example.application.data.repository.StatusRepository;
  8. import org.springframework.stereotype.Service;
  9. import java.util.List;
  10. @Service 1
  11. public class CrmService {
  12. private final ContactRepository contactRepository;
  13. private final CompanyRepository companyRepository;
  14. private final StatusRepository statusRepository;
  15. public CrmService(ContactRepository contactRepository,
  16. CompanyRepository companyRepository,
  17. StatusRepository statusRepository) { 2
  18. this.contactRepository = contactRepository;
  19. this.companyRepository = companyRepository;
  20. this.statusRepository = statusRepository;
  21. }
  22. public List<Contact> findAllContacts(String stringFilter) {
  23. if (stringFilter == null || stringFilter.isEmpty()) { 3
  24. return contactRepository.findAll();
  25. } else {
  26. return contactRepository.search(stringFilter);
  27. }
  28. }
  29. public long countContacts() {
  30. return contactRepository.count();
  31. }
  32. public void deleteContact(Contact contact) {
  33. contactRepository.delete(contact);
  34. }
  35. public void saveContact(Contact contact) {
  36. if (contact == null) { 4
  37. System.err.println("Contact is null. Are you sure you have connected your form to the application?");
  38. return;
  39. }
  40. contactRepository.save(contact);
  41. }
  42. public List<Company> findAllCompanies() {
  43. return companyRepository.findAll();
  44. }
  45. public List<Status> findAllStatuses(){
  46. return statusRepository.findAll();
  47. }
  48. }
  1. The @Service annotation will make this a Spring-managed service that you can inject into your view.

  2. Use Spring constructor injection to autowire the database repositories.

  3. Check if there is an active filter, return either all contacts or use the repository to filter based on the string.

  4. Service classes often include validation and other business rules before making the data persistent. Here, you check that you aren’t accidentally trying to save a null object.

Implementing Filtering in the Repository

Add the search() method to the contacts repository to provide the service class with the required method for filtering contacts.

ContactRepository.java

  1. public interface ContactRepository extends JpaRepository<Contact, Long> {
  2. @Query("select c from Contact c " +
  3. "where lower(c.firstName) like lower(concat('%', :searchTerm, '%')) " +
  4. "or lower(c.lastName) like lower(concat('%', :searchTerm, '%'))") 1
  5. List<Contact> search(@Param("searchTerm") String searchTerm); 2
  6. }
  1. Uses the @Query annotation to define a custom query. In this case, it checks if the string matches the first or the last name, and ignores the case. The query uses Java Persistence Query Language (JPQL) which is an SQL-like language for querying JPA-managed databases.

Note that you do not need to implement the method. Spring Data will provide the implementation based on the query.

Using the Backend Service From the View

You can now inject the CrmService into the list view to access the backend.

ListView.java

  1. package com.example.application.views.list;
  2. import com.example.application.data.entity.Contact;
  3. import com.example.application.data.service.CrmService;
  4. import com.vaadin.flow.component.Component;
  5. import com.vaadin.flow.component.button.Button;
  6. import com.vaadin.flow.component.grid.Grid;
  7. import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
  8. import com.vaadin.flow.component.orderedlayout.VerticalLayout;
  9. import com.vaadin.flow.component.textfield.TextField;
  10. import com.vaadin.flow.data.value.ValueChangeMode;
  11. import com.vaadin.flow.router.PageTitle;
  12. import com.vaadin.flow.router.Route;
  13. import com.vaadin.flow.theme.Theme;
  14. import java.util.Collections;
  15. @Route(value = "")
  16. @Theme(themeFolder = "flowcrmtutorial")
  17. @PageTitle("Contacts | Vaadin CRM")
  18. public class ListView extends VerticalLayout {
  19. Grid<Contact> grid = new Grid<>(Contact.class);
  20. TextField filterText = new TextField();
  21. ContactForm form;
  22. CrmService service;
  23. public ListView(CrmService service) { 1
  24. this.service = service;
  25. addClassName("list-view");
  26. setSizeFull();
  27. configureGrid();
  28. configureForm();
  29. add(getToolbar(), getContent());
  30. updateList(); 2
  31. }
  32. private Component getContent() {
  33. HorizontalLayout content = new HorizontalLayout(grid, form);
  34. content.setFlexGrow(2, grid);
  35. content.setFlexGrow(1, form);
  36. content.addClassNames("content");
  37. content.setSizeFull();
  38. return content;
  39. }
  40. private void configureForm() {
  41. form = new ContactForm(service.findAllCompanies(), service.findAllStatuses()); 3
  42. form.setWidth("25em");
  43. }
  44. private void configureGrid() {
  45. grid.addClassNames("contact-grid");
  46. grid.setSizeFull();
  47. grid.setColumns("firstName", "lastName", "email");
  48. grid.addColumn(contact -> contact.getStatus().getName()).setHeader("Status");
  49. grid.addColumn(contact -> contact.getCompany().getName()).setHeader("Company");
  50. grid.getColumns().forEach(col -> col.setAutoWidth(true));
  51. }
  52. private HorizontalLayout getToolbar() {
  53. filterText.setPlaceholder("Filter by name...");
  54. filterText.setClearButtonVisible(true);
  55. filterText.setValueChangeMode(ValueChangeMode.LAZY);
  56. filterText.addValueChangeListener(e -> updateList()); 4
  57. Button addContactButton = new Button("Add contact");
  58. HorizontalLayout toolbar = new HorizontalLayout(filterText, addContactButton);
  59. toolbar.addClassName("toolbar");
  60. return toolbar;
  61. }
  62. private void updateList() { 5
  63. grid.setItems(service.findAllContacts(filterText.getValue()));
  64. }
  65. }
  1. Autowire CrmService through the constructor. Save it in a field, so you can access it from other methods.

  2. Call updateList() once you have constructed the view.

  3. Use the service to fetch companies and statuses.

  4. Call updateList() any time the filter changes.

  5. updateList() sets the grid items by calling the service with the value from the filter text field.

Build the project, refresh the browser, and verify that you can now see contacts in the grid. Try filtering the contents by typing into the filter text field.

The grid displays 4 contacts after filtering with the string

migration assistance

Download free e-book.
The complete guide is also available in an easy-to-follow PDF format.

https://pages.vaadin.com/en/build-a-modern-web-app-with-spring-boot-vaadin-pdf

Open in anew tab

Show code

render-banner.ts

  1. export class RenderBanner extends HTMLElement {
  2. connectedCallback() {
  3. this.renderBanner();
  4. }
  5. renderBanner() {
  6. let bannerWrapper = document.getElementById('tocBanner');
  7. if (bannerWrapper) {
  8. return;
  9. }
  10. let tocEl = document.getElementById('toc');
  11. // Add an empty ToC div in case page doesn't have one.
  12. if (!tocEl) {
  13. const pageTitle = document.querySelector(
  14. 'main > article > header[class^=PageHeader-module--pageHeader]'
  15. );
  16. tocEl = document.createElement('div');
  17. tocEl.classList.add('toc');
  18. pageTitle?.insertAdjacentElement('afterend', tocEl);
  19. }
  20. // Prepare banner container
  21. bannerWrapper = document.createElement('div');
  22. bannerWrapper.id = 'tocBanner';
  23. tocEl?.appendChild(bannerWrapper);
  24. // Banner elements
  25. const text = document.querySelector('.toc-banner-source-text')?.innerHTML;
  26. const link = document.querySelector('.toc-banner-source-link')?.textContent;
  27. const bannerHtml = `<div class='toc-banner'>
  28. <a href='${link}'>
  29. <div class="toc-banner--img"></div>
  30. <div class='toc-banner--content'>${text}</div>
  31. </a>
  32. </div>`;
  33. bannerWrapper.innerHTML = bannerHtml;
  34. // Add banner image
  35. const imgSource = document.querySelector('.toc-banner-source .image');
  36. const imgTarget = bannerWrapper.querySelector('.toc-banner--img');
  37. if (imgSource && imgTarget) {
  38. imgTarget.appendChild(imgSource);
  39. }
  40. }
  41. }