• Stars
    star
    108
  • Rank 321,259 (Top 7 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated 15 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Creating CRUD UI with Vaadin :: Use Vaadin and Spring Data JPA to build a dynamic UI

This guide walks you through the process of building an application that uses a Vaadin-based UI on a Spring Data JPA based backend.

What You Will build

You will build a Vaadin UI for a simple JPA repository. What you will get is an application with full CRUD (Create, Read, Update, and Delete) functionality and a filtering example that uses a custom repository method.

You can follow either of two different paths:

  • Starting from the initial project that is already in the project.

  • Making a fresh start.

The differences are discussed later in this document.

Starting with Spring Initializr

You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.

Note
You can also fork the project from Github and open it in your IDE or other editor.

Manual Initialization (optional)

If you want to initialize the project manually rather than use the links shown earlier, follow the steps given below:

  1. Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.

  2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.

  3. Click Dependencies and select Vaadin, Spring Data JPA and H2 Database.

  4. Click Generate.

  5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.

Note
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.

Create the Backend Services

This guide is a continuation from Accessing Data with JPA. The only differences are that the entity class has getters and setters and the custom search method in the repository is a bit more graceful for end users. You need not read that guide to walk through this one, but you can if you wish.

If you started with a fresh project, you need to add entity and repository objects. If you started from the initial project, these object already exist.

The following listing (from src/main/java/com/example/crudwithvaadin/Customer.java) defines the customer entity:

link:complete/src/main/java/com/example/crudwithvaadin/Customer.java[]

The following listing (from src/main/java/com/example/crudwithvaadin/CustomerRepository.java) defines the customer repository:

link:complete/src/main/java/com/example/crudwithvaadin/CustomerRepository.java[]

The following listing (from src/main/java/com/example/crudwithvaadin/CrudWithVaadinApplication.java) shows the application class, which creates some data for you:

link:complete/src/main/java/com/example/crudwithvaadin/CrudWithVaadinApplication.java[]

Vaadin Dependencies

If you checked out the initial project, or you created your project with initializr, you have all necessary dependencies already set up. However, the rest of this section describes how to add Vaadin support to a fresh Spring project. Spring’s Vaadin integration contains a Spring Boot starter dependency collection, so you need add only the following Maven snippet (or a corresponding Gradle configuration):

link:complete/pom.xml[]

The example uses a newer version of Vaadin than the default one brought in by the starter module. To use a newer version, define the Vaadin Bill of Materials (BOM) as follows:

link:complete/pom.xml[]

In developer mode, the dependency is enough, but When you are building for production, you need to enable your app for production builds.

Tip
By default, Gradle does not support BOMs, but there is a handy plugin for that. Check out the build.gradle build file for an example of how to accomplish the same thing.

Define the Main View class

The main view class (called MainView in this guide) is the entry point for Vaadin’s UI logic. In Spring Boot applications, if you annotate it with @Route, it is automatically picked up and shown at the root of your web application. You can customize the URL where the view is shown by giving a parameter to the @Route annotation. The following listing (from the initial project at src/main/java/com/example/crudwithvaadin/MainView.java) shows a simple β€œHello, World” view:

link:initial/src/main/java/com/example/crudwithvaadin/MainView.java[]

List Entities in a Data Grid

For a nice layout, you can use the Grid component. You can pass the list of entities from a constructor-injected CustomerRepository to the Grid by using the setItems method. The body of your MainView would then be as follows:

@Route
public class MainView extends VerticalLayout {

	private final CustomerRepository repo;
	final Grid<Customer> grid;

	public MainView(CustomerRepository repo) {
		this.repo = repo;
		this.grid = new Grid<>(Customer.class);
		add(grid);
		listCustomers();
	}

	private void listCustomers() {
		grid.setItems(repo.findAll());
	}

}
Tip
If you have large tables or lots of concurrent users, you most likely do not want to bind the whole dataset to your UI components.
Although Vaadin Grid lazy loads the data from the server to the browser, the preceding approach keeps the whole list of data in the server memory. To save some memory, you could show only the topmost results by employing paging or using lazy loading, for examply using the grid.setItems(VaadinSpringDataHelpers.fromPagingRepository(repo)) method.

Filtering the Data

Before the large data set becomes a problem to your server, it is likely to cause a headache for your users as they try to find the relevant row to edit. You can use a TextField component to create a filter entry. To do so, first modify the listCustomer() method to support filtering. The following example (from the complete project in src/main/java/com/example/crudwithvaadin/MainView.java) shows how to do so:

link:complete/src/main/java/com/example/crudwithvaadin/MainView.java[]
Note
This is where Spring Data’s declarative queries come in handy. Writing findByLastNameStartsWithIgnoringCase is a single line definition in the CustomerRepository interface.

You can hook a listener to the TextField component and plug its value into that filter method. The ValueChangeListener is called automatically as a user types because you define the ValueChangeMode.LAZY on the filter text field. The following example shows how to set up such a listener:

TextField filter = new TextField();
filter.setPlaceholder("Filter by last name");
filter.setValueChangeMode(ValueChangeMode.LAZY);
filter.addValueChangeListener(e -> listCustomers(e.getValue()));
add(filter, grid);

Define the Editor Component

As Vaadin UIs are plain Java code, you can write re-usable code from the beginning. To do so, define an editor component for your Customer entity. You can make it be a Spring-managed bean so that you can directly inject the CustomerRepository into the editor and tackle the Create, Update, and Delete parts or your CRUD functionality. The following example (from src/main/java/com/example/crudwithvaadin/CustomerEditor.java) shows how to do so:

link:complete/src/main/java/com/example/crudwithvaadin/CustomerEditor.java[]

In a larger application, you could then use this editor component in multiple places. Also note that, in large applications, you might want to apply some common patterns (such as MVP) to structure your UI code.

Wire the Editor

In the previous steps, you have already seen some basics of component-based programming. By using a Button and adding a selection listener to Grid, you can fully integrate your editor into the main view. The following listing (from src/main/java/com/example/crudwithvaadin/MainView.java) shows the final version of the MainView class:

link:complete/src/main/java/com/example/crudwithvaadin/MainView.java[]

You can see your Vaadin application running at http://localhost:8080

Summary

Congratulations! You have written a full-featured CRUD UI application by using Spring Data JPA for persistence. And you did it without exposing any REST services or having to write a single line of JavaScript or HTML.

More Repositories

1

tut-spring-security-and-angular-js

Spring Security and Angular:: A tutorial on how to use Spring Security with a single page application with various backend architectures, ranging from a simple single server to an API gateway with OAuth2 authentication.
TypeScript
1,695
star
2

gs-rest-service

Building a RESTful Web Service :: Learn how to create a RESTful web service with Spring.
Java
1,391
star
3

tut-spring-boot-kotlin

Building web applications with Spring Boot and Kotlin :: Learn how to easily build and test web applications with Spring, Kotlin, Junit 5 and JPA
Kotlin
914
star
4

tut-spring-boot-oauth2

Spring Boot and OAuth2:: A tutorial on "social" login and single sign on with Facebook and Github
Java
905
star
5

gs-spring-boot

Building an Application with Spring Boot :: Learn how to build an application with minimal configuration.
Java
897
star
6

tut-react-and-spring-data-rest

React.js and Spring Data REST :: A tutorial based on the 5-part blog series by Greg Turnquist
JavaScript
884
star
7

gs-spring-boot-docker

Spring Boot with Docker :: Learn how to create a Docker container from a Spring Boot application with Maven or Gradle
Java
619
star
8

gs-messaging-stomp-websocket

Using WebSocket to build an interactive web application :: Learn how to the send and receive messages between a browser and the server over a WebSocket
Java
528
star
9

getting-started-guides

Getting Started Guide template :: The template for new guides and also the place to request them.
Java
519
star
10

tut-rest

Building REST services with Spring :: Learn how to easily build RESTful services with Spring
Java
516
star
11

gs-uploading-files

Uploading Files :: Learn how to build a Spring application that accepts multi-part file uploads.
Java
471
star
12

gs-securing-web

Securing a Web Application :: Learn how to protect your web application with Spring Security.
Java
351
star
13

gs-multi-module

Creating a Multi Module Project :: Learn how to build a library and package it for consumption in a Spring Boot application
Java
329
star
14

gs-serving-web-content

Serving Web Content with Spring MVC :: Learn how to create a web page with Spring MVC and Thymeleaf.
Java
275
star
15

gs-batch-processing

Creating a Batch Service :: Learn how to create a basic batch-driven solution.
Java
243
star
16

gs-accessing-data-jpa

Accessing Data with JPA :: Learn how to work with JPA data persistence using Spring Data JPA.
Java
229
star
17

top-spring-security-architecture

Spring Security Architecture:: Topical guide to Spring Security, how the bits fit together and how they interact with Spring Boot
226
star
18

gs-consuming-rest

Consuming a RESTful Web Service :: Learn how to retrieve web page data with Spring's RestTemplate.
Java
195
star
19

gs-accessing-data-mysql

Accessing data with MySQL :: Learn how to set up and manage user accounts on MySQL and how to configure Spring Boot to connect to it at runtime.
Java
192
star
20

gs-messaging-rabbitmq

Messaging with RabbitMQ :: Learn how to create a simple publish-and-subscribe application with Spring and RabbitMQ.
Java
183
star
21

gs-testing-web

Testing the Web Layer :: Learn how to test Spring Boot applications and MVC controllers.
Java
178
star
22

gs-maven

Building Java Projects with Maven :: Learn how to build a Java project with Maven.
Java
165
star
23

gs-reactive-rest-service

Building a Reactive RESTful Web Service :: Learn how to create a RESTful web service with Reactive Spring and consume it with WebClient.
Java
162
star
24

gs-gradle

Building Java Projects with Gradle :: Learn how to build a Java project with Gradle.
Java
161
star
25

gs-producing-web-service

Producing a SOAP web service :: Learn how to create a SOAP-based web service with Spring.
Java
153
star
26

gs-service-registration-and-discovery

Service Registration and Discovery :: Learn how to register and find services with Eureka
Java
151
star
27

gs-accessing-data-rest

Accessing JPA Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
146
star
28

gs-consuming-web-service

Consuming a SOAP web service :: Learn how to create a client that consumes a WSDL-based service
Java
136
star
29

gs-accessing-data-mongodb

Accessing Data with MongoDB :: Learn how to persist data in MongoDB.
Java
135
star
30

gs-scheduling-tasks

Scheduling Tasks :: Learn how to schedule tasks with Spring.
Java
129
star
31

gs-validating-form-input

Validating Form Input :: Learn how to perform form validation with Spring.
Java
124
star
32

gs-rest-service-cors

Enabling Cross Origin Requests for a RESTful Web Service :: Learn how to create a RESTful web service with Spring that support Cross-Origin Resource Sharing (CORS).
Java
110
star
33

gs-gateway

Building a Gateway :: Learn how to configure a gateway
Java
106
star
34

gs-authenticating-ldap

Authenticating a User with LDAP :: Learn how to secure an application with LDAP.
Java
97
star
35

gs-messaging-jms

Messaging with JMS :: Learn how to publish and subscribe to messages using a JMS broker.
Java
90
star
36

gs-async-method

Creating Asynchronous Methods :: Learn how to create asynchronous service methods.
Java
86
star
37

gs-relational-data-access

Accessing Relational Data using JDBC with Spring :: Learn how to access relational data with Spring.
Java
80
star
38

gs-messaging-redis

Messaging with Redis :: Learn how to use Redis as a message broker.
Java
80
star
39

gs-actuator-service

Building a RESTful Web Service with Spring Boot Actuator :: Learn how to create a RESTful Web service with Spring Boot Actuator.
Java
74
star
40

gs-rest-hateoas

Building a Hypermedia-Driven RESTful Web Service :: Learn how to create a hypermedia-driven RESTful Web service with Spring.
Java
73
star
41

gs-accessing-mongodb-data-rest

Accessing MongoDB Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
70
star
42

gs-caching

Caching Data with Spring :: Learn how to cache data in memory with Spring
Java
67
star
43

gs-centralized-configuration

Centralized Configuration :: Learn how to manage application settings from an external, centralized source
Java
58
star
44

gs-accessing-data-r2dbc

Accessing data with R2DBC :: Learn how to access relational data with the reactive protocol R2DBC
Java
47
star
45

gs-spring-boot-kubernetes

Spring Boot Kubernetes :: Deploy a Spring Boot application to Kubernetes :: spring-boot,spring-framework
Java
46
star
46

tut-spring-webflux-kotlin-rsocket

Spring Boot with Kotlin Coroutines and RSocket :: Build a chat application with Reactive Web services from Spring, Kotlin, WebFlux and RSocket
JavaScript
45
star
47

gs-handling-form-submission

Handling Form Submission :: Learn how to create and submit a web form with Spring.
Java
45
star
48

gs-spring-data-reactive-redis

Accessing Data Reactively with Redis :: Learn how to reactively interface with Redis and Spring Data
Java
35
star
49

gs-sts

Working a Getting Started guide with STS :: Learn how to import a Getting Started guide with Spring Tool Suite (STS).
Shell
34
star
50

gs-consuming-rest-angularjs

Consuming a RESTful Web Service with AngularJS :: Learn how to retrieve web page data with AngularJS.
HTML
32
star
51

gs-accessing-data-neo4j

Accessing Data with Neo4j :: Learn how to persist objects and relationships in Neo4j's NoSQL data store.
Java
29
star
52

quoters

Spring Boot quotation service to support REST-based guides
Java
28
star
53

gs-spring-cloud-loadbalancer

Client-Side Load-Balancing with Spring Cloud LoadBalancer :: Dynamically select correct instance for the request :: spring-cloud,spring-cloud-loadbalancer,spring-cloud-commons
Java
28
star
54

gs-convert-jar-to-war

Converting a Spring Boot JAR Application to a WAR :: Learn how to convert your Spring Boot JAR-based application to a WAR file.
Shell
22
star
55

gs-graphql-server

Building a GraphQL service :: Learn how to build a GraphQL service with Spring for GraphQL.
Java
21
star
56

top-spring-on-kubernetes

Spring on Kubernetes :: Topic guide to Spring and Kubernetes
Java
20
star
57

gs-managing-transactions

Managing Transactions :: Learn how to wrap key parts of code with transactions.
Java
19
star
58

gs-messaging-gcp-pubsub

Messaging with Google Cloud Pub/Sub :: Learn how to exchange messages using Spring Integration channel adapters and Google Cloud Pub/Sub
Java
18
star
59

gs-vault-config

Vault Configuration :: Learn how to store and retrieve application configuration details in HashiCorp Vault
Java
16
star
60

getting-started-macros

Collection of macros used to support getting started guides
15
star
61

gs-testing-restdocs

Creating API Documentation with Restdocs :: Learn how to generate documentation for HTTP endpoints using Spring Restdocs
Java
14
star
62

gs-intellij-idea

Working a Getting Started guide with IntelliJ IDEA :: Learn how to work a Getting Started guide with IntelliJ IDEA.
Shell
14
star
63

gs-spring-boot-for-azure

Deploying a Spring Boot app to Azure :: Learn how to deploy a Spring Boot app to Azure.
Shell
14
star
64

gs-contract-rest

Consumer Driven Contracts :: Learn how to with contract stubs and consuming that contract from another Spring application
Java
13
star
65

gs-integration

Integrating Data :: Learn how to build an application that uses Spring Integration to fetch data, process it, and write it to a file.
Java
12
star
66

gs-cloud-circuit-breaker

Spring Cloud Circuit Breaker Guide :: How to Use Spring Cloud Circuit Breaker
Java
12
star
67

gs-accessing-neo4j-data-rest

Accessing Neo4j Data with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
11
star
68

gs-consuming-rest-jquery

Consuming a RESTful Web Service with jQuery :: Learn how to retrieve web page data with jQuery.
HTML
10
star
69

gs-caching-gemfire

Caching Data with Pivotal GemFire :: Learn how to cache data in GemFire.
Java
9
star
70

gs-accessing-data-gemfire

Accessing Data in Pivotal GemFire :: Learn how to build an application using Gemfire's data fabric.
Java
9
star
71

gs-accessing-vault

Accessing Vault :: Learn how to use Spring Vault to load secrets from HashiCorp Vault
Java
7
star
72

gs-accessing-gemfire-data-rest

Accessing Data in Pivotal GemFire with REST :: Learn how to work with RESTful, hypermedia-based data persistence using Spring Data REST.
Java
6
star
73

gs-spring-cloud-stream

Spring Cloud Stream :: Learn how to build and test Spring Cloud Stream Applications with RabbitMQ and Apache Kafka
Java
5
star
74

gs-accessing-data-cassandra

Accessing Data with Cassandra :: Learn how to persist data in Cassandra.
Java
5
star
75

issue-aggregator

List issues from multiple GH repo
Kotlin
3
star
76

gs-spring-cloud-task

Spring Cloud Task :: Learn how to build and test Spring Cloud Task Applications
Java
3
star
77

gs-tanzu-observability

Observability with Spring :: Learn how to send application metrics to Tanzu Observability
Java
3
star
78

drone-aggregator

Get a snapshot view of your CI jobs hosted at drone.io
SCSS
2
star
79

gs-sts-cloud-foundry-deployment

Deploying to Cloud Foundry from STS :: Learn how to deploy a Spring application to Cloud Foundry from STS
Shell
2
star
80

gs-guides-with-vscode

Building a Guide with VS Code :: Learn how to import and work with a Spring Getting Started Guide in VS Code.
Shell
2
star
81

gs-spring-cloud-dataflow

Spring Cloud Data Flow :: Learn how to build, deploy and launch streaming and batch data pipelines using Spring Cloud Data Flow
2
star
82

topical-guides

Spring Topical Guides:: The template for new topical guides on spring.io and also the place to request them
2
star
83

top-observing-graphql-in-action

Observing GraphQL in action :: Tutorial on GraphQL and Observability
Java
1
star