Loading

Accessing Data with Spring Data JPA and MySQL

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 the 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 spring-data-starter-data-jpa and mysql-connector-java dependencies to access MySQL database with Spring Data JPA.

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

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

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'mysql:mysql-connector-java'

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

Configuring Database Connection Properties

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

# MySQL connection properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/rest-service
spring.datasource.username=root
spring.datasource.password=root@pass

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

Create User Model Class

package net.codinghub.restservice.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(length = 50)
    private String name;

    @Column(length = 50)
    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

@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

package net.codinghub.restservice.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import net.codinghub.restservice.model.User;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
    // CRUD refers Create, Read, Update, Delete
}

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

You will be now able to use save(), findOne(), findAll(), count(), delete() etc.

Create Request File

We have used the UserRequest class file to handle POST data.

package net.codinghub.restservice.request;

public class UserRequest {

    private String name;

    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

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.

package net.codinghub.restservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import net.codinghub.restservice.model.User;
import net.codinghub.restservice.repository.UserRepository;
import net.codinghub.restservice.request.UserRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping(value = "/all", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Iterable<User>> getAllUsers() {
        Iterable<User> users = userRepository.findAll();

        return new ResponseEntity<>(users, HttpStatus.OK);
    }

    @PostMapping(value = "/create", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> addNewUser(@RequestBody UserRequest request) {

        User model = new User();
        model.setName(request.getName());
        model.setEmail(request.getEmail());

        User newUser = userRepository.save(model);

        return new ResponseEntity<User>(newUser, HttpStatus.OK);
    }
}

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 ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

java -jar target/rest-service-0.0.1-SNAPSHOT.jar

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

java -jar build/libs/rest-service-0.0.1-SNAPSHOT.jar

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.

To skip the basics, do the following:

Related Articles