CRUD operations with Spring Data JPA

Getting into Spring Boot, part 3 CRUD operations with Spring Data JPA

In our Spring Boot articles, we have passed so far, only in the Code generated, static test data to Views. Real records, but usually from a database. In the third part of this series, we therefore implement a database connection.

Company to the topic

The H2 Console allows, via a Browser interface to an SQL database access.The H2 Console allows, via a Browser interface to an SQL database access.


In the current operating data are stored mostly in large and reliable server systems such as Oracle, SQL Server or MySQL. During outsourcing development, it may be quickly and easily. Here are the H2 Database Engine is a good choice.

Integrating H2 Database Engine

H2 can be used either as a server application, install or even just as a Jar via Maven-dependency in the Page Object Model (POM) to integrate. In addition to specifying the database to the Starter is in addition spring-boot-starter-data-jpa needed, which incorporates the Java Persistence API. It is for Persisting Java objects to relational databases:


Those who prefer to use the wizard in the “Spring Tool Suite”, you can of course do that too: right-click on the POM and then Spring > Edit starter select. The required dependencies hot H2 Database and Spring Data JPA.

Controller: The H2-Console

The operation of the database is done via a Web console, which must be enabled prior to use and configured. This is done by the following two entries in the file under src/main/resources:


The “mem” in the Datasource URL causes a Restart of H2 in the In-Memory mode. The data will not be stored permanently, they are lost after Closing the application. During Test and development is a practical Option.

The Login window of the H2 console in the Browser.The Login window of the H2 console in the Browser.

(Image: Dr. Koller / H2 Database Engine)

After restarting the application, the Login Dialog of the H2 console is “http://localhost:8080/h2-console” available. The first is a Test of the connection using the Test Connection is recommended. The JDBC URL in corresponds to the assigned spring.datasource.url. The Default User name is sa and no password needed. After the successful Test, you have to login with the help of the Connect button and the console is familiar to you.

Interior view of the H2-console.Interior view of the H2-console.

(Image: Dr. Koller / H2 Database Engine)

In the large text box to the right database queries to formulate. In the tree view on the left of all existing database objects to find. The tables in the Schema INFORMATION_SCHEMA contains metadata about the structure of the database, which is not of interest here. The User sa is to be found in the folder Users. We currently don’t own database entities are present. Time to change that!

Of the class for the entity

In the previous second part of the Spring-Boot-series have been created, such as the Person class to pass to the View. The class can be achieved by minor Changes to the entity to carry:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Person {
private Long id;
private String firstname;
private String lastname;
   public Long getId() {
return id;
   public void setId(Long id) { = id;
   public String getFirstname() {
return firstname;
   public void setFirstname(String firstname) {
this.firstname = firstname;
   public String getLastname() {
return lastname;
   public void setLastname(String lastname) {
this.lastname = lastname;

Annotation @Entity_ marks the class as an entity. The new member variable “id” is used as a primary key in the database, and is @Id_ characterized. Since the value of the Spring should automatically be awarded to you also Generated value annotated and strategy CAR used.

The H2 database with Person table.The H2 database with Person table.

(Image: Dr. Koller / H2 Database Engine)

The Getter and Setter can be re – Source > Generate getters and Setters in Eclipse or Spring Tools Suite to generate. That’s it, the entity is ready to use. After a restart, you will find the corresponding table in the database, however, without contents.

Initial data with data.sql

To Insert initial database contents, Spring provides a simple way: the Insert Statements in the file data.sql (for example, under src/main/resources) are performed automatically. Here are two members of the family pattern of man are written to the database:

INSERT INTO person (id, firstname, lastname) VALUES (-1, 'Max', 'Mustermann');
INSERT INTO person (id, firstname, lastname) VALUES (-2, 'Erika', 'Mustermann');

Since it is a simple SQL-Inserts without Spring functionality must be the primary forgive key by Hand. Here we use negative values, so they do not collide with the later automatically generated primary key.

Test data in H2.Test data in H2.

(Image: Dr. Koller / H2 Database Engine)

In the H2 Console, the test data after the restart with a Select query. You can click on the table “Person”, the Statement is then inserted in the front provided in figure automatically to the right in the text field.

For Database interactions in two ways: firstly, the JDBC Template, a kind of Wrapper around the old JDBC access, or, more elegant, with the help of Spring Data Repositories exist in Spring. Repositories are a persistence abstraction, the access to Domain objects in the Form of Collections allow. The Pattern is a bit similar to the more well-known DAO Pattern.

The implementation is quite simple. To create a Repository Interface for the corresponding Domain class, so here are Person. The Interface inherits from one of several Standard Interfaces, for example, the CrudRepository, and is typed with the domain class (Person) and to the data type of the ID (Long):

public interface PersonRepository extends CrudRepository<Person, Long>{}

CRUD stands for Create, Read, Update and Delete, so the common database operations. The implementation of the Interface provided by Spring, it includes these operations. To try this out, you get a Repository Bean in a Controller, inject, and can then use the inherited methods. In the following example, the previously inserted test data set is findById() and the matching Primary Key read:

public class PersonController {
PersonRepository personRepository;
public String home() {
Optional<Person> person = personRepository.findById(-1L);
if(person.isPresent()) {
return person.get().getLastname();
} else {
return "Keine Person mit dieser Id gefunden :-(";

The Method findAll() find all the entities in the Repository:

List<Person> persons = (List<Person>) personRepository.findAll();

Of course you can also create new records, the corresponding Repository method is called save:

Person newPerson = new Person();

Test data with automatically generated primary key.Test data with automatically generated primary key.

(Image: Dr. Koller / H2 Database Engine)

The primary key is assigned automatically. As you can see in the Screenshot, numbering starts with the number One.

The save method is also used in the Update to the application. An existing entity is assigned to a different attribute value, and then save saved.

The Delete is still missing. The Method delete(entity) deletes an entity with the given reference. If this is not known, one can deleteById(id) also the primary key as a criterion to use.

Thus, the four CRUD operations are complete. In the next part of the series of articles we deal with more sophisticated Queries.


Ready to see us in action:

More To Explore
Enable registration in settings - general
Have any project in mind?

Contact us: