There are three basic entity relationships:-
A Single post can have multiple comments by this way we can apply one-to-many Mapping
Clone the repo from here:- Click here
Import Maven based project in any of your Favourite IDE.
Open in Browser
Access H2 Database.
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);
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<>();
Comments are mapped by the ID of the Post on which they are commented. As you can see in the below images.
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