DEV Community

Cover image for Spring Boot One To Many Mapping Demo With H2 database
Atharva Siddhabhatti
Atharva Siddhabhatti

Posted on

Spring Boot One To Many Mapping Demo With H2 database

There are three basic entity relationships:-

  • One-to-One
  • One-to-Many/Many-to-one
  • Many-to-Many

A Single post can have multiple comments by this way we can apply one-to-many Mapping

Installation

Clone the repo from here:- Click here

Import Maven based project in any of your Favourite IDE.

./mvnw spring-boot:run
Enter fullscreen mode Exit fullscreen mode

Output

Open in Browser

Access H2 Database.

http://localhost:8080/h2-console
Enter fullscreen mode Exit fullscreen mode

Usage

MainClass.java

run() method is run when the application is started. The data is added in the database.

    Post post = new Post("Spring Boot Post Title","Spring Boot Post Description");
        Comment comment1 = new Comment("Thanks for uploading");
        Comment comment2 = new Comment("Comment2 test");
        Comment comment3 = new Comment("Comment3 test");

        post.getComments().add(comment1);
        post.getComments().add(comment2);
        post.getComments().add(comment3);

        postRepository.save(post);
Enter fullscreen mode Exit fullscreen mode

Post.java

Id column is used to map the post and comments together.

@OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "post_Comment_id",referencedColumnName = "id")
    List<Comment> comments = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

Output

Comments are mapped by the ID of the Post on which they are commented. As you can see in the below images.

output1
output2

Configuration

application.properties

spring.jpa.show-sql = true

# Enabling H2 Console
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.defer-datasource-initialization=true
spring.h2.console.enabled=true

# Enable Web Access
spring.h2.console.settings.web-allow-others=true
Enter fullscreen mode Exit fullscreen mode

Discussion (0)