Integration of SpringBoot with MySQL using Spring JPA

Reading Time: 2 minutes

In this blog, we will learn how we can create CRUD using MySQL as a database using JPA.
Create Spring-boot Project using https://start.spring.io/  and make sure to add the following dependencies.

Configure MySQL
Before starting with the example, just add the following configurations for MYSQL in the application.properties file

Let’s take a simple example and persists the following JSON document in the database.

{
"id" : "1",
"name" : "Bhawna",
"age": 24
}

Add Entity Class
Add the following entity class that represents the above JSON document

@Entity annotation specifies that this POJO is an entity that needs to persist in the database.
@Table annotation allows us to provide the details of the table like name, schema, and constraints. In the above example, we are just mentioning the table name.
@Column annotation maps the POJO field with the table field.
@Id annotation specifies that the particular field will be treated as Primary key.

Create Repository

import org.springframework.data.jpa.repository.JpaRepository;
        import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<StudentInfo, String> {

}

Here, JPARepository extends PagingAndSortingRepository and QueryByExampleExecutor. And internally PagingAndSortingRepository extends CrudRepository. Therefore JPARepository provides all the methods of PagingAndSortingRepository, QueryByExampleExecutor, and CrudRepository.

We can also add derivable query methods in the repository. For example:

//It will find the Student Information by name.
StudentInfo findByName(String name);

Add Controller
Now, what we need is the Controller class that simply invoke our repository method.

So, you can see that in the above example, we are using some inbuilt methods provided by JPA and derivable query method.

Conclusion:

So, it’s pretty easy to build Spring-boot application with JPA. First of all, configure MySQL properties in the application.properties file. Add the entity that you want to persist in DB. Add repository that can consist of some derivable methods and controller that integrate the repository with the rest API.
Hope this is helpful. Please feel free to provide your suggestions 🙂

References:
https://spring.io/guides/gs/accessing-data-mysql/

 

blog_footer

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!