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 postGET /posts— Retrieve all postsGET /find/{id}— Retrieve a post by IDPUT /update— Update an existing postDELETE /delete?id=— Delete a post by ID
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
Show All Posts
Find Post
Delete Post
Update Post
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 /addpostinserts a new post usingpostDao.save(). - Read —
GET /postsreturns all posts andGET /find/{id}returns a single post. - Update —
PUT /updateupdates 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(), anddelete(). - @RestController combines
@Controllerand@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:
Post a Comment