One-to-Many Unidirectional Mapping in Spring Boot and JPA

Last updated on March 14th, 2024

This topic teaches us how to implement one-to-many unidirectional mapping between two JPA entities using Spring Boot, Spring Data JPA, H2 database and Lombok        

one-to-many_unidirectional_mapping

In one-to-many mapping, one row is mapped with multiple rows in another table. For example, a post has multiple comments. We will create a restful web service example to implement one-to-many unidirectional mapping using the Spring Boot application. In this example, we will have four API endpoints two for saving the data into the database and another for getting data from the database. Let’s begin to implement

Table of Contents
   1. Create a Spring Boot Starter Project(One-to-Many Unidirectional Mapping)
   2. Maven Dependency
   3. Define the H2 database configuration
   4. Create Entity
   5. Create Repository
   6. Create Service
   7. Create Controller
   8. Run the Spring Boot application
   9. Conclusion

1. Create a Spring Boot Starter Project(One-to-Many Unidirectional Mapping)

Add the following dependencies: 
    • Spring Web 
    • Lombok
    • H2 Database
    • Spring Data JPA

Project Structure

one_to_many_unidirectional_mapping_project_structure

2. Maven Dependency

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springjava</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <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>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>    
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3. Define the H2 database configuration

We are configuring the H2 database for this implementation of One-to-Many Unidirectional Mapping in the application.properties file.

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

4. Create Entity

Post.java

package com.springjava.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import lombok.Data;
@Data
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String desc;
@OneToMany
@JoinColumn(name = "post_id")
private List<Comment> commentList;
}

→ We used @OneToMany annotation to make the relationship with the Comment entity class.
→ We used @JoinColumn annotation to define a foreign key column with the mentioned name.
→ We used the @Data annotation of Lombok to automatically generate constructor, setter and getter methods of the Java Bean class. 

Comment.java

package com.springjava.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Data
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String msg;
}

5. Create Repository

PostRepository.java

package com.springjava.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springjava.entity.Post;
public interface PostRepository extends JpaRepository<Post, Integer> {
}

CommentRepository.java

package com.springjava.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.springjava.entity.Comment;
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}

6. Create Service

PostService.java

package com.springjava.service;
import java.util.List;
import com.springjava.entity.Post;
public interface PostService {
void save(Post post);
List<Post> findAll();
Post findById(Integer id);
}

PostServiceImpl.java

package com.springjava.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springjava.entity.Post;
import com.springjava.repository.PostRepository;
@Service
public class PostServiceImpl implements PostService {
@Autowired
PostRepository postRepo;
@Override
public void save(Post post) {
postRepo.save(post);
}
@Override
public List<Post> findAll() {
return postRepo.findAll();
}
@Override
public Post findById(Integer id) {
return postRepo.findById(id).get();
    }
}

CommentService.java

package com.springjava.service;
import java.util.List;
import com.springjava.entity.Comment;
public interface CommentService {
void save(Comment comment);
List<Comment> findAll();
}

CommentServiceImpl.java

package com.springjava.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springjava.entity.Comment;
import com.springjava.repository.CommentRepository;
@Service
public class CommentServiceImpl implements CommentService {
@Autowired
CommentRepository commentRepo;
@Override
public void save(Comment comment) {
commentRepo.save(comment);
}
@Override
public List<Comment> findAll() {
return commentRepo.findAll();
    }
}

7. Create Controller

PostController.java

package com.springjava.controller;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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 com.springjava.entity.Post;
import com.springjava.service.PostService;
@RestController
@RequestMapping("/api")
public class PostController {
  @Autowired
  PostService postService;
  @PostMapping("/post/save")
  public ResponseEntity <?> save(@RequestBody Post post) {
    Map<String, Object> respMap = new LinkedHashMap <String, Object>();
    //saving post into db
    postService.save(post);
    respMap.put("status", 1);
    respMap.put("message", "Record is Saved Successfully!");
    return new ResponseEntity< >(respMap, HttpStatus.CREATED);
  }
  @GetMapping("/post/list")
  public ResponseEntity <?> getPosts() {
    Map <String, Object> respMap = new LinkedHashMap < String, Object>();
    List <Post> posts = postService.findAll();
    if (!posts.isEmpty()) {
      respMap.put("status", 1);
      respMap.put("data", posts);
      return new ResponseEntity< >(respMap, HttpStatus.OK);
    } else {
      respMap.clear();
      respMap.put("status", 0);
      respMap.put("message", "Data is not found");
      return new ResponseEntity< >(respMap, HttpStatus.NOT_FOUND);
    }
  }
}

CommentController.java

package com.springjava.controller;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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 com.springjava.entity.Comment;
import com.springjava.entity.Post;
import com.springjava.service.CommentService;
import com.springjava.service.PostService;
@RestController
@RequestMapping("/api")
public class CommentController {
  @Autowired
  PostService postService;
  @Autowired
  CommentService commentService;
  @PostMapping("/comment/{postId}/save")
  public ResponseEntity <?> save(@PathVariable("postId") Integer id, @RequestBody Comment comment) {
    Map <String, Object> respMap = new LinkedHashMap <String, Object>();
    Post post = postService.findById(id);
    post.getCommentList().add(comment);
    commentService.save(comment);
    respMap.put("status", 1);
    respMap.put("message", "Record is Saved Successfully!");
    return new ResponseEntity < > (respMap, HttpStatus.CREATED);
  }
  @GetMapping("/comment/list")
  public ResponseEntity <?> getComments() {
    Map <String, Object> respMap = new LinkedHashMap <String, Object>();
    List <Comment> comments = commentService.findAll();
    if (!comments.isEmpty()) {
      respMap.put("status", 1);
      respMap.put("data", comments);
      return new ResponseEntity < > (respMap, HttpStatus.OK);
    } else {
      respMap.clear();
      respMap.put("status", 0);
      respMap.put("message", "Data is not found");
      return new ResponseEntity < >(respMap, HttpStatus.NOT_FOUND);
    }
  }
}

8. Run the Spring Boot application

To run this application one-to-many unidirectional mapping Right-click on the DemoApplication.java then click on Run As and select Java Application.
To test the API on the Postman
Url: http://localhost:8080/api/post/save

testing_post_mapping_api_postman

Url: http://localhost:8080/api/comment/1/save

testing_post_mapping_api_postman

Url: http://localhost:8080/api/post/list

testing_get_mapping_api_postman

Url: http://localhost:8080/api/comment/list

testing_get_mapping_api_postman

To check the H2 database we can browse this URL “http://localhost:8080/h2-console” on the browser to view the tables in the H2 database created by this application(one-to-many unidirectional mapping).

h2_database_console
See both tables below here:

h2_database_table
h2_database_table

9. Conclusion

In this topic, we learnt about how to implement one-to-many unidirectional mapping in spring boot, spring data JPA, Lombok and h2 database with rest API example.

Leave a Comment