Reader small image

You're reading from  Full Stack Development with Spring Boot and React - Third Edition

Product typeBook
Published inApr 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781801816786
Edition3rd Edition
Languages
Right arrow
Author (1)
Juha Hinkula
Juha Hinkula
author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula

Right arrow

Chapter 3: Using JPA to Create and Access a Database

This chapter covers how to use Java Persistent API (JPA) with Spring Boot and how to define a database by using entity classes. In the first phase, we will be using the H2 in-memory database for development and demonstration purposes. H2 is an in-memory SQL database that is good for fast development or demonstration purposes. In the second phase, we will move from H2 to use MariaDB. This chapter also describes the creation of CRUD repositories and a one-to-many connection between database tables.

In this chapter, we will cover the following topics:

  • Basics of ORM, JPA, and Hibernate
  • Creating the entity classes
  • Creating CRUD repositories
  • Adding relationships between tables
  • Setting up the MariaDB database

Technical requirements

Java SDK version 8 or higher is necessary to use Spring Boot (http://www.oracle.com/technetwork/java/javase/downloads/index.html). The Spring Boot application we created in previous chapters is required.

A MariaDB installation is necessary to create the database application (https://downloads.mariadb.org/).

The code for this chapter can be found at the following GitHub link: https://github.com/PacktPublishing/Full-Stack-Development-with-Spring-Boot-and-React/tree/main/Chapter03.

Check out the following video to see the Code in Action: https://bit.ly/3lVCuVe

Basics of ORM, JPA, and Hibernate

Object Relational Mapping (ORM) is a technique that allows you to fetch from and manipulate a database by using an object-oriented programming paradigm. ORM is really good for programmers because it relies on object-oriented concepts rather than database structures. It also makes development much faster and reduces the amount of source code. ORM is mostly independent of databases, and developers don't have to worry about vendor-specific SQL statements.

Java Persistent API (JPA) provides object-relational mapping for Java developers. The JPA entity is a Java class that presents the structure of a database table. The fields of an entity class present the columns of the database tables.

Hibernate is the most popular Java-based JPA implementation and is used in Spring Boot by default. Hibernate is a mature product and is widely used in large-scale applications.

Next, we will start to implement our first entity class using the H2 database...

Creating the entity classes

An entity class is a simple Java class that is annotated with JPA's @Entity annotation. Entity classes use the standard JavaBean naming convention and have proper getter and setter methods. The class fields have private visibility.

JPA creates a database table called by the name of the class when the application is initialized. If you want to use some other name for the database table, you can use the @Table annotation in your entity class.

At the beginning of this chapter, we will use the H2 database (https://www.h2database.com/), which is embedded in our in-memory database. To be able to use JPA and the H2 database, we have to add the following dependencies to the pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>...

Creating CRUD repositories

The Spring Boot Data JPA provides a CrudRepository interface for Create, Read, Update, and Delete (CRUD) operations. It provides CRUD functionalities to our entity class.

Let's create our repository in the domain package, as follows:

  1. Create a new class called CarRepository in the com.packt.cardatabase.domain package and modify the file according to the following code snippet:
    package com.packt.cardatabase.domain;
    import org.springframework.data.repository
    .CrudRepository;
    public interface CarRepository extends CrudRepository<Car, Long> {
    }

CarRepository now extends the Spring Boot JPA CrudRepository interface. The <Car, Long> type arguments define that this is the repository for the Car entity class and that the type of the ID field is Long.

The CrudRepository interface provides multiple CRUD methods that we can now start to use. The following table lists the most commonly used methods:

Figure 3.7...

Adding relationships between tables

Next, we create a new table called owner that has a one-to-many relationship with the car table. In this case, a one-to-many relationship means that the owner can own multiple cars, but a car can only have one owner. The following Unified Modeling Language (UML) diagram shows the relationship between the tables:

Figure 3.12 – OneToMany relationship

The following are the steps to create a new table:

  1. First, we must create the Owner entity and repository in the com.packt.cardatabase.domain package. The Owner entity and repository are created in a similar way to the Car class.

The following is the source code of the Owner entity class:

// Owner.java
package com.packt.cardatabase.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Owner {
    @Id
   ...

Setting up a MariaDB database

Now, we will switch our database from H2 to MariaDB. The database tables are still created automatically by JPA. However, before we run our application, we have to create a database for it. In this section, we will be using the one-to-many relationship from the previous section.

The database can be created by using HeidiSQL. Open HeidiSQL and follow these steps:

  1. Right-click inside the database list.
  2. Then, select Create new | Database:

Figure 3.19 – Create new – Database

  1. Let's name our database cardb. After clicking OK, you should see the new cardb database in the database list:

Figure 3.20 – The cardb database

  1. In Spring Boot, add a MariaDB Java client dependency to the pom.xml file and remove the H2 dependency since we don't need it anymore:
    <dependency>
        <groupId>org.mariadb.jdbc</groupId>
      ...

Summary

In this chapter, we used JPA to create our Spring Boot application database. First, we created entity classes, which are mapped to database tables. Then, we created CrudRepository for our entity class, which provides CRUD operations for the entity. After that, we managed to add some demo data to our database by using CommandLineRunner. We also created one-to-many relationships between two entities. At the beginning of this chapter, we used the H2 in-memory database, while at the end, we switched the database to MariaDB.

In the next chapter, we will create a RESTful web service for our backend. We will also look at testing the RESTful web service with the curl command-line tool, and also by using Postman GUI.

Questions

Answer the following questions to test your knowledge of this chapter:

  1. What are ORM, JPA, and Hibernate?
  2. How can you create an entity class?
  3. How can you create CrudRepository?
  4. What does CrudRepository provide for your application?
  5. How can you create a one-to-many relationship between tables?
  6. How can you add demo data to a database with Spring Boot?
  7. How can you access the H2 console?
  8. How can you connect your Spring Boot application to MariaDB?

Further reading

Packt has other great resources for Spring Boot:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot and React - Third Edition
Published in: Apr 2022Publisher: PacktISBN-13: 9781801816786
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Juha Hinkula

Juha Hinkula is a software development lecturer at Haaga-Helia University of Applied Sciences in Finland. He received an MSc degree in Computer Science from the University of Helsinki and he has over 17 years of industry experience in software development. Over the past few years, he has focused on modern full stack development. He is also a passionate mobile developer with Android-native technology, and also uses React Native.
Read more about Juha Hinkula