Spring JPA repository for the above Entities and configuration of Mysql in the application.yml
In this section we will learn about:
Spring JPA repository
First, we need to add MySQL dependency in POM.xml.
And after adding dependencies update maven.
Next, create an application.yml file under the resources folder if not present, and add the below configuration.
• driver-class: It's the driver used to connect with MySQL.
• url: It is the address of the MySQL database that contains the hostname, port, and database name.
• username: user of the MySQL server
• password: password of the MySQL server
Spring JPA repository
Spring Data is a Spring-based programming model for data access. It reduces the amount of code needed for working with databases and datastores. It consists of several modules. The Spring Data JPA simplifies the development of Spring applications that use JPA technology.
With Spring Data, we define a repository interface for each domain entity in the application. A repository contains methods for performing CRUD operations(create, read, update and delete), sorting, and paginating data. @Repository is a marker annotation, which indicates that the underlying interface is a repository. A repository is created by extending specific repository interfaces, such as CrudRepository, PagingAndSortingRepository, or JpaRepository.
Now, we will create repositories for each entity using JpaRepository.
JpaRepository is a JPA specific extension of the Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains an API for basic CRUD operations and also API for pagination and sorting.
We need to create an interface named “YogaUserRepository” which extends “JpaRepository<YogaUser, Long>”.
“JpaRepository<>” is a generic class with 2 parameters. The first parameter is the entity class using the repository i.e. “YogaUser” and the second is the data type of the entity ID, i.e. Long.
We extend this class because it has inbuilt methods which are helpful in CRUD operations etc. We can also add our methods to this interface if needed.
We should annotate this interface with “@Repository” to mark it as a repository.
b) Similarly, we will create other repositories.