Reader small image

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

Product typeBook
Published inOct 2023
PublisherPackt
ISBN-139781805122463
Edition4th Edition
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

Using JPA to Create and Access a Database

This chapter covers how to use Jakarta Persistence 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 database. 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 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

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/. We went through the installation steps in Chapter 1.

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

Basics of ORM, JPA, and Hibernate

ORM and JPA are widely used techniques in software development for handling relational databases. You don’t have to write complex SQL queries; instead, you can work with objects, which is more natural for Java developers. In this way, ORM and JPA can speed up your development process by reducing the time you spend writing and debugging SQL code. Many JPA implementations can also generate a database schema automatically based on your Java entity classes. In brief:

  • 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.
  • Jakarta...

Before you begin: Join our book community on Discord

Give your feedback straight to the author himself and chat to other early readers on our Discord server (find the "full-stack-dev-spring-boot-3-react-4e" channel under EARLY ACCESS SUBSCRIPTION).

https://packt.link/EarlyAccess

Qr code Description automatically generated

This chapter covers how to use Jakarta 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 17 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-3-and-React-Fourth-Edition/tree/main/Chapter03

Basics of ORM, JPA, and Hibernate

ORM and JPA are widely used techniques in software development for handling relational databases. You don’t have to write complex SQL queries, instead you can work with objects.

  • 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.
  • Jakarta Persistent API (JPA, formerly Java Persistence API) provides object-relational mapping for Java developers. Th 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...

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-memory database. To be able to use JPA and the H2 database, we have to add the following dependencies to the build.gradle file:

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 
  developmentOnly 'org.springframework.boot:spring-boot-devtools'
  runtimeOnly 'com.h2database...

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 interface 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:

Table 3.1: CRUD methods

If the method returns only...

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.14: OneToMany relationship

The following are the steps to create a new table:

  1. First, we must create the Owner entity and repository classes 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 jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Owner {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long ownerid...

Setting up a MariaDB database

Now, we will switch our database from H2 to MariaDB. In this book, we are using MariaDB version 10. 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 (or DBeaver, if you are using Linux or macOS) Open HeidiSQL and follow these steps:

  1. Activate the top database connection name (Unamed) and right-click inside the database list.
  2. Then, select Create new | Database:

    Figure 3.21: Create new – Database
  3. Let's name our database cardb. After clicking OK, you should see the new cardb database in the database list:

    Figure 3.22: The cardb database
  4. In Spring Boot, add a MariaDB Java client dependency to the build.gradle file and remove the H2 dependency since we don't need it anymore. Remember to refresh your Gradle project after...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Development with Spring Boot 3 and React - Fourth Edition
Published in: Oct 2023Publisher: PacktISBN-13: 9781805122463
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