Atharva Siddhabhatti
Atharva Siddhabhatti's Blog

Atharva Siddhabhatti's Blog

Spring Boot One To Many Mapping Demo With H2 database

Atharva Siddhabhatti's photo
Atharva Siddhabhatti
·Oct 15, 2021·

1 min read

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

Output

Open in Browser

Access H2 Database.

http://localhost:8080/h2-console

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);

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<>();

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
 
Share this