Spring Boot CRUD with JPA

Spring Boot CRUD with JPA Tutorial | REST API CRUD Example with MySQL

Spring Boot CRUD with JPA Tutorial

Author: Deep Singh | Category: Java, Spring Boot, Spring Data JPA, REST API

Introduction

In this tutorial, you'll learn how to build a complete CRUD REST API using Spring Boot and Spring Data JPA with a MySQL database. CRUD stands for Create, Read, Update, and Delete — the four basic operations performed on persistent data.

By the end, you'll have a working REST API with the following endpoints:

  • POST /addpost — Create a new post
  • GET /posts — Retrieve all posts
  • GET /find/{id} — Retrieve a post by ID
  • PUT /update — Update an existing post
  • DELETE /delete?id= — Delete a post by ID

Project Structure

Spring Boot CRUD with JPA project structure showing controller, dao, and model packages
Figure 1: Spring Boot CRUD with JPA project structure

Post.java (Entity)

The JPA entity representing a post stored in the posts table.

package com.deepsingh44.demo.model;

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

@Entity
@Table(name = "posts")
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String title;
    private String description;

    public int getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

PostDao.java (Repository)

Spring Data JPA repository that provides built-in CRUD operations for the Post entity.

package com.deepsingh44.demo.dao;

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

import com.deepsingh44.demo.model.Post;

@Repository
public interface PostDao extends JpaRepository<Post, Integer> {

}

HelloController.java (REST Controller)

The REST controller exposing CRUD endpoints for the Post entity. It uses PostDao to interact with the database.

package com.deepsingh44.demo.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.deepsingh44.demo.dao.PostDao;
import com.deepsingh44.demo.model.Post;

@RestController
public class HelloController {

    @Autowired
    private PostDao postDao;

    @PostMapping("/addpost")
    public String hello(@RequestBody Post post) {
        postDao.save(post);
        return "Successfully Added";
    }

    @GetMapping("/posts")
    public List<Post> getAllPost() {
        return postDao.findAll();
    }

    @GetMapping("/find/{id}")
    public Post getPostById(@PathVariable int id) {
        Optional<Post> opt = postDao.findById(id);
        return (!opt.isEmpty()) ? opt.get() : new Post();
    }

    @DeleteMapping("/delete")
    public String deletePostById(@RequestParam int id) {
        String msg = "Not Deleted";
        Post post = getPostById(id);
        if (post.getId() != 0) {
            postDao.delete(post);
            msg = "Successfully Deleted";
        }
        return msg;
    }

    @PutMapping("/update")
    public Post updatePost(@RequestBody Post mypost) {
        Post post = getPostById(mypost.getId());
        return (post.getId() == 0) ? post : postDao.save(mypost);
    }
}

WeekendHelloWorldApplication.java

The main Spring Boot application entry point.

package com.deepsingh44.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WeekendHelloWorldApplication {

    public static void main(String[] args) {
        SpringApplication.run(WeekendHelloWorldApplication.class, args);
    }
}

application.properties

Configure the server port, MySQL datasource, and JPA/Hibernate properties.

server.port=8081

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/bootdb
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

pom.xml

Required Maven dependencies for Spring Boot Web, Spring Data JPA, and MySQL.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Output Screens

Add Post

POST /addpost endpoint testing in Postman showing successful post creation
Figure 2: Add Post — POST /addpost

Show All Posts

GET /posts endpoint returning a list of all posts in JSON format
Figure 3: Show All Posts — GET /posts

Find Post

GET /find/{id} endpoint returning a single post by its ID
Figure 4: Find Post — GET /find/{id}

Delete Post

DELETE /delete endpoint removing a post and returning success message
Figure 5: Delete Post — DELETE /delete?id=

Update Post

PUT /update endpoint updating an existing post and returning the updated record
Figure 6: Update Post — PUT /update

Conclusion

In this tutorial, we built a complete Spring Boot CRUD REST API using Spring Data JPA and MySQL. We covered all four CRUD operations:

  • Create — POST /addpost inserts a new post using postDao.save().
  • Read — GET /posts returns all posts and GET /find/{id} returns a single post.
  • Update — PUT /update updates an existing post after checking its existence.
  • Delete — DELETE /delete?id= removes a post by its ID.

Key takeaways:

  • JpaRepository provides built-in CRUD methods such as save(), findAll(), findById(), and delete().
  • @RestController combines @Controller and @ResponseBody, making it ideal for building REST APIs.
  • @RequestBody binds the incoming JSON payload to a Java object.
  • @PathVariable and @RequestParam extract values from the URL path and query string respectively.
  • spring.jpa.hibernate.ddl-auto=update automatically creates/updates database tables based on entity classes.

You can extend this example by adding pagination, sorting, custom query methods, validation, exception handling, or a service layer between the controller and the repository. This CRUD pattern forms the foundation of nearly every Spring Boot REST application.

No comments: