Lab#SB08-2: Vaadin

Spring Boot Restaurant Management Vaadin

Spring-Boot
lab
Spring Boot
Author

albertprofe

Published

Wednesday, January 10, 2024

Modified

Monday, October 7, 2024

📘 Spring Boot Lab#SB00-2: RestaurantManager Vaadin We are going to evolve the current Java SE Restaurant project into a Spring Boot Restaurant Management System with an H2 DB and web interface using Vaadin.


1 From RestaurantProject to RestaurantManagement

2 Create a new Spring Boot project & H2 DB

  • Create a new Spring Boot project: The first step would be to create a new Spring Boot project in the preferred IDE or text editor.

The project can be created using Spring Initializr, which will create the necessary file structure and dependencies.

  • Configure the H2 database: In the newly created project, configure the H2 database by adding:
    • the H2 dependency in the pom.xml file,
    • and also create a new application.properties file
    • set the database properties such as:
      • the database URL,
      • username,
      • and password.

2.1 Model & Entities

  • Create a Menu Entity: To represent a menu item in the restaurant management system, create a Menu @Entity

It could include attributes such as name, price, description, category (appetizer, main course, dessert, etc.), and availability status.

  • Create a Customer Entity: To represent a customer in the system, create a Customer entity that includes attributes such as customer ID, name, phone number, email, and reservation history.

  • Create Booking Entity: To represent a booking in the system, create a Booking entity that includes attributes such as booking date, time, number of people, tables, and associated customer.

  • Create Staff Entity: To represent staff members in the system, create a Staff entity that includes attributes such as staff ID, name, position, shift schedules, and assigned tables.

2.2 Domains: @Controller, @Service and @Repository

  • Create Repositories: To access the data stored in the database, create repositories for each entity. The repositories will provide the methods to create, read, update, and delete the data.

  • Create Services: Create services that will implement the business logic of the system by calling the repository methods.

The services will provide the methods to search for available tables, make a reservation, update menu items, process orders, manage staff schedules, handle customer feedback, and generate reports on restaurant performance.

  • Create Controllers: Create controllers that will handle the requests from the Vaadin UI by calling the service methods.

The controllers will provide the methods to create a customer account, search for available tables, make a reservation, view and update menu items, place an order, manage staff schedules, submit customer feedback, and generate various reports.

3 Vaadin

3.1 Modern Java framework for building web applications

Vaadin is a web application framework for Java that allows developers to build modern, interactive web applications using Java without having to write HTML, CSS, or JavaScript. Here are some key points about Vaadin:

3.2 Create Vaadin Views

  • Create Vaadin Views: To create the web interface of the system, create Vaadin views for each of the main functionalities. The views will be used to display the data and handle user interactions.

Vaadin allows you to create rich, interactive UIs using Java code. It provides a wide range of UI components and layouts that you can use to build your application’s interface.

Example of a simple Vaadin view:

@Route("menu")
public class MenuView extends VerticalLayout {
    private final MenuService menuService;

    public MenuView(MenuService menuService) {
        this.menuService = menuService;
        
        H1 title = new H1("Restaurant Menu");
        Grid<Menu> grid = new Grid<>(Menu.class);
        grid.setItems(menuService.getAllMenuItems());
        
        add(title, grid);
    }
}

This view creates a page with a title and a grid showing all menu items.

3.3 Key Vaadin Concepts

  1. Server-side Architecture: Vaadin primarily runs on the server, which means your business logic stays secure and you can leverage the full power of Java.

  2. Component-based UI: Build UIs by combining and customizing existing components or creating your own.

  3. Data Binding: Easily bind UI components to data sources, including JPA entities.

  4. Themes and Styling: Customize the look and feel of your application using CSS and Vaadin’s theming capabilities.

  5. Integration with Spring Boot: Vaadin integrates seamlessly with Spring Boot, allowing you to use Spring’s dependency injection and other features.

4 Code: CustomerView

The CustomerView class is a Vaadin-based web application view for managing customer information in a restaurant.

4.1 Key Components

  • Route: Default view of the application (@Route("")).
  • Layout: Extends VerticalLayout for vertical arrangement.
  • Grid: Displays customer data in a table format.
  • Form Fields: Text fields for name, email, and phone number.
  • Buttons: Save and Delete buttons for managing customers.
  • Binder: For data binding between form fields and the Customer object.

4.2 Main Features

  1. Layout Structure
    • 3-column layout for responsive design.
    • Center column contains interactive components.
  2. Customer Data Display
    • Grid shows customer details (ID, name, email, phone number).
    • Allows selection of customers from the grid.
  3. Form for Customer Management
    • Input fields for customer information.
    • Save button to add/update customers.
    • Delete button to remove selected customers.
  4. Data Binding
    • Uses Binder for two-way data binding.
    • Updates form fields when a customer is selected.
  5. Event Handling
    • Save button saves/updates customer data.
    • Delete button removes the selected customer.
    • Grid selection updates form with selected customer’s data.
  6. Repository Integration
    • Uses CustomerRepository for CRUD operations.

4.3 Key Methods

  • createMainLayout(): Sets up UI components and layout.
  • setupEventListeners(): Configures event handlers.
  • saveCustomer(): Saves/updates customer records.
  • deleteCustomer(): Deletes selected customer records.
  • clearForm(): Resets form fields.
  • refreshGrid(): Updates grid with latest customer data.

This view provides an easy-to-use interface for managing customer information in a restaurant

4.4 CustomerView.java

Code
CustomerView.java
package dev.example.restaurant.view;


import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
import dev.example.restaurant.model.Customer;
import dev.example.restaurant.repository.CustomerRepository;
import java.util.UUID;

@Route("")
public class CustomerView extends VerticalLayout {

    private final CustomerRepository customerRepository;
    private final Grid<Customer> grid = new Grid<>(Customer.class);
    private final TextField name = new TextField("Name");
    private final TextField email = new TextField("Email");
    private final TextField phoneNumber = new TextField("Phone Number");
    private final Button save = new Button("Save");
    private final Button delete = new Button("Delete");
    private final Binder<Customer> binder = new Binder<>(Customer.class);

    public CustomerView(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;

        // Set up the main view properties
        setSizeFull();
        setPadding(false);
        setSpacing(false);

        // Create and add the main layout
        add(createMainLayout());

        // Set up data binding
        binder.bindInstanceFields(this);

        // Set up event listeners
        setupEventListeners();

        // Initialize the view
        clearForm();
        refreshGrid();
    }

    // Method to create the main layout
    private Component createMainLayout() {
        // Create the 3-column layout
        HorizontalLayout mainLayout = new HorizontalLayout();
        mainLayout.setSizeFull();
        mainLayout.setPadding(false);
        mainLayout.setSpacing(false);

        // Left column (empty for spacing)
        VerticalLayout leftColumn = new VerticalLayout();
        leftColumn.setWidth("20%");

        // Center column (contains all the components)
        VerticalLayout centerColumn = new VerticalLayout();
        centerColumn.setWidth("60%");
        centerColumn.setAlignItems(Alignment.CENTER);

        // Right column (empty for spacing)
        VerticalLayout rightColumn = new VerticalLayout();
        rightColumn.setWidth("20%");

        // Set up the grid
        grid.setColumns("id", "name", "email", "phoneNumber");
        grid.setSizeFull();

        // Create a form layout
        HorizontalLayout formLayout = new HorizontalLayout(name, email, phoneNumber);
        formLayout.setWidth("100%");
        formLayout.setJustifyContentMode(JustifyContentMode.CENTER);

        // Create a button layout
        HorizontalLayout buttonLayout = new HorizontalLayout(save, delete);
        buttonLayout.setJustifyContentMode(JustifyContentMode.CENTER);

        // Add components to the center column
        centerColumn.add(
                new H2("Customer Management"),
                grid,
                formLayout,
                buttonLayout
        );

        // Add all columns to the main layout
        mainLayout.add(leftColumn, centerColumn, rightColumn);

        return mainLayout;
    }

    // Method to set up event listeners
    private void setupEventListeners() {
        save.addClickListener(e -> saveCustomer());
        delete.addClickListener(e -> deleteCustomer());

        grid.asSingleSelect().addValueChangeListener(event -> {
            if (event.getValue() != null) {
                binder.setBean(event.getValue());
            } else {
                clearForm();
            }
        });
    }

    // Methods to save, delete, and clear the form
    private void saveCustomer() {
        Customer customer = binder.getBean();
        if (customer == null) {
            customer = new Customer();
        }
        if (customer.getId() == null || customer.getId().isEmpty()) {
            customer.setId(UUID.randomUUID().toString());
        }
        binder.writeBeanIfValid(customer);
        customerRepository.save(customer);
        clearForm();
        refreshGrid();
    }

    // Method to delete a customer
    private void deleteCustomer() {
        Customer customer = binder.getBean();
        if (customer != null) {
            customerRepository.delete(customer);
            clearForm();
            refreshGrid();
        }
    }

    // Method to clear the form
    private void clearForm() {
        binder.setBean(new Customer());
    }

    // Method to refresh the grid
    private void refreshGrid() {
        grid.setItems(customerRepository.findAll());
    }
}

5 Test

Test the system

Test the system by running it and making sure that all the functionalities work as expected. This includes testing reservation creation, menu management, order processing, staff scheduling, and report generation.

6 Code and output