Spring Boot Hibernate One-to-Many CRUD REST API Tutorial

In this tutorial, we will demonstrate how to set up a one-to-many relationship between Post and Comment entities using Spring Boot and Hibernate, and expose CRUD operations through a REST API for a blog application.
Spring Boot Hibernate One-to-Many CRUD REST API Tutorial

Prerequisites

  1. Java Development Kit (JDK) 11 or higher: Ensure JDK is installed and configured on your system.
  2. Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or any other IDE.
  3. Maven: Ensure Maven is installed and configured on your system.

Step 1: Create a Spring Boot Project

  1. Open your IDE and create a new Spring Boot project.
  2. Use Spring Initializr or manually create the pom.xml file to include Spring Boot and other required dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>spring-boot-blog-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.0</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Explanation

  • spring-boot-starter-data-jpa: Includes Spring Data JPA with Hibernate.
  • spring-boot-starter-web: Includes Spring MVC for building web applications.
  • h2: An in-memory database for testing purposes.

Step 2: Configure the Application Properties

Configure the application.properties file to set up the H2 database.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Step 3: Create the Post Entity Class

Create a package named com.example.entity and a class named Post.

package com.example.entity;

import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Comment> comments = new HashSet<>();

    public Post() {}

    public Post(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Set<Comment> getComments() {
        return comments;
    }

    public void setComments(Set<Comment> comments) {
        this.comments = comments;
    }

    public void addComment(Comment comment) {
        comments.add(comment);
        comment.setPost(this);
    }

    public void removeComment(Comment comment) {
        comments.remove(comment);
        comment.setPost(null);
    }

    @Override
    public String toString() {
        return "Post{id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + '}';
    }
}

Explanation

  • @Entity: Marks the class as an entity.
  • @Id: Marks the field as the primary key.
  • @GeneratedValue: Specifies the strategy for generating values for the primary key.
  • @OneToMany: Defines a one-to-many relationship with the Comment entity.
  • mappedBy: Specifies the field in the Comment entity that owns the relationship.
  • cascade: Specifies the cascade operations.
  • orphanRemoval: Specifies whether to remove orphaned entities.

Step 4: Create the Comment Entity Class

Create a class named Comment in the same package.

package com.example.entity;

import jakarta.persistence.*;

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

    public Comment() {}

    public Comment(String content) {
        this.content = content;
    }

    public Long getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    @Override
    public String toString() {
        return "Comment{id=" + id + ", content='" + content + '\'' + '}';
    }
}

Explanation

  • @Entity: Marks the class as an entity.
  • @Id: Marks the field as the primary key.
  • @GeneratedValue: Specifies the strategy for generating values for the primary key.
  • @ManyToOne: Defines a many-to-one relationship with the Post entity.
  • @JoinColumn: Specifies the foreign key column.

Step 5: Create Repository Interfaces

Create a package named com.example.repository and interfaces for Post and Comment.

package com.example.repository;

import com.example.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {}
package com.example.repository;

import com.example.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {}

Step 6: Create Service Classes

Create a package named com.example.service and service classes for Post and Comment.

package com.example.service;

import com.example.entity.Post;
import com.example.entity.Comment;
import com.example.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {
    @Autowired
    private PostRepository postRepository;

    public Post save(Post post) {
        return postRepository.save(post);
    }

    public List<Post> findAll() {
        return postRepository.findAll();
    }

    public Post findById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

    public void deleteById(Long id) {
        postRepository.deleteById(id);
    }

    public Post addComment(Long postId, Comment comment) {
        Post post = findById(postId);
        if (post != null) {
            post.addComment(comment);
            return save(post);
        }
        return null;
    }

    public Post removeComment(Long postId, Long commentId) {
        Post post = findById(postId);
        if (post != null) {
            Comment comment = post.getComments().stream().filter(c -> c.getId().equals(commentId)).findFirst().orElse(null);
            if (comment != null) {
                post.removeComment(comment);
                return save(post);
            }
        }
        return null;
    }
}
package com.example.service;

import com.example.entity.Comment;
import com.example.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    public Comment save(Comment comment) {
        return commentRepository.save(comment);
    }

    public List<Comment> findAll() {
        return commentRepository.findAll();
    }

    public Comment findById(Long id) {
        return commentRepository.findById(id).orElse(null);
    }

    public void deleteById(Long id)

 {
        commentRepository.deleteById(id);
    }
}

Step 7: Create Controller Classes

Create a package named com.example.controller and controller classes for Post and Comment.

package com.example.controller;

import com.example.entity.Post;
import com.example.entity.Comment;
import com.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }

    @GetMapping
    public List<Post> getAllPosts() {
        return postService.findAll();
    }

    @GetMapping("/{id}")
    public Post getPostById(@PathVariable Long id) {
        return postService.findById(id);
    }

    @DeleteMapping("/{id}")
    public void deletePost(@PathVariable Long id) {
        postService.deleteById(id);
    }

    @PostMapping("/{postId}/comments")
    public Post addComment(@PathVariable Long postId, @RequestBody Comment comment) {
        return postService.addComment(postId, comment);
    }

    @DeleteMapping("/{postId}/comments/{commentId}")
    public Post removeComment(@PathVariable Long postId, @PathVariable Long commentId) {
        return postService.removeComment(postId, commentId);
    }
}
package com.example.controller;

import com.example.entity.Comment;
import com.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @PostMapping
    public Comment createComment(@RequestBody Comment comment) {
        return commentService.save(comment);
    }

    @GetMapping
    public List<Comment> getAllComments() {
        return commentService.findAll();
    }

    @GetMapping("/{id}")
    public Comment getCommentById(@PathVariable Long id) {
        return commentService.findById(id);
    }

    @DeleteMapping("/{id}")
    public void deleteComment(@PathVariable Long id) {
        commentService.deleteById(id);
    }
}

Step 8: Create Main Application Class

Create a package named com.example and a class named SpringBootBlogExampleApplication.

package com.example;

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

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

Step 9: Run the Application

  1. Run the SpringBootBlogExampleApplication class.
  2. Use an API client (e.g., Postman) or a web browser to test the endpoints.

Testing the Endpoints

  1. Create a Post:

    • URL: POST /posts
    • Body:
      {
        "title": "First Post",
        "content": "This is the content of the first post"
      }
      
  2. Create Comments:

    • URL: POST /comments
    • Body:
      {
        "content": "This is the first comment"
      }
      
    • Body:
      {
        "content": "This is the second comment"
      }
      
  3. Add Comments to Post:

    • URL: POST /posts/{postId}/comments
    • Body:
      {
        "content": "This is the first comment"
      }
      
    • Body:
      {
        "content": "This is the second comment"
      }
      
  4. Get All Posts:

    • URL: GET /posts
  5. Get Post by ID:

    • URL: GET /posts/{id}
  6. Get All Comments:

    • URL: GET /comments
  7. Get Comment by ID:

    • URL: GET /comments/{id}
  8. Delete Post by ID:

    • URL: DELETE /posts/{id}
  9. Delete Comment by ID:

    • URL: DELETE /comments/{id}

Conclusion

You have successfully created an example using Spring Boot and Hibernate to demonstrate a one-to-many relationship in a blog application context. This tutorial covered setting up a Spring Boot project, configuring Hibernate, creating entity classes with a one-to-many relationship, and performing CRUD operations through RESTful endpoints.


Comments