Accessing Data with Spring Data JPA and MySQL

In this article, you will learn how to access data with Spring Data JPA and MySQL. You might have found the previous article very much useful and this article is an extension of Building a RESTful Web Service in Spring Boot.

Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. We will see an example of how to access data from a database in a spring boot application using spring data JPA.

Dependencies

You need and dependencies to access MySQL database with Spring Data JPA.

If you are using Maven, add the following dependencies to your file:

For the Gradle project, add the following dependencies to your file:

You may like: How to add & update Canonical URL in Angular

Configuring Database Connection Properties

Update file under the src/main/resources directory with the following content:

You will need to create a database named rest-service in MySQL, and change the & properties as per your MySQL installation.

Create User Model Class

@Entity annotation defines that a class can be mapped to a table.

@Table annotation is used to provide the details of the table that this entity will be mapped to.

@GeneratedValue annotation is used to define the primary key generation strategy. In the above case, we have declared the primary key to be an Auto Increment field.

@Column annotation is used to define the properties of the column that will be mapped to the annotated field.

Create a Repository

@Repository is a stereotype for the persistence layer and tells Spring to bootstrap the repository during the component scan.

You will be now able to use , , , , etc.

Create Request File

We have used the class file to handle POST data.

You may like: Handle CORS error in Lumen

Create User Controller

The Final Step — We’ll now create the REST APIs for creating, retrieving a User.

The @RequestBody annotation is used to bind the request body with a method parameter.

You may like: How to write Graphql Query for Strapi application using Angular

Run the Application

As we are using Maven build, we can run the application by using . Alternatively, you can build the JAR file with and then run the JAR file, as follows:

If you use Gradle, you can run the application by using . Alternatively, we can build the JAR file by using and then run the JAR file:

Summary

Congratulations! You have successfully developed a Spring Boot application that uses Spring Data JPA with MySQL database to store, access, delete and update data.

Originally published at https://www.codinghub.net.

Coding Hub — Learn & Build Your Career

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store