"Welcome To Ashok IT" "Spring Boot and MicroServices" Topic : Association (ManyToOne) Date : 05/11/2024 (Session - 59) _____________________________________________________________________________________________________________________________ One To Many Bidirectional ========================= * A @OneToMany bidirectional association is a relationship between two entities in an object-oriented programming environment, often implemented in frameworks like Java's Java Persistence API (JPA) or Hibernate. * This association signifies that one entity has a one-to-many relationship with another entity. In other words, one instance of the source entity is associated with multiple instances of the target entity. * In a Bidirectional association, both ends of the relationship are aware of each other. This means that not only can you navigate from the source entity to the target entity (one side), but you can also navigate back from the target entity to the source entity (many side). * In the context of object-relational mapping (ORM) and database modeling, the mappedBy attribute plays a crucial role in establishing bidirectional associations between entities. It is commonly used in frameworks like Java Persistence API (JPA) or Hibernate. * The mappedBy attribute is typically used on the non-owning side of a bidirectional relationship to define how the association is mapped to the owning side. One To Many Bidirectional Application ===================================== Post.java ========= package com.ashokit.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; @Entity @Table(name="ashokit_posts") public class Post { @Id @Column(name = "post_id") @GeneratedValue(strategy = GenerationType.AUTO) private int postId; @Column(name="post_title", nullable = false) private String postTitle; @Column(name="created_date",nullable = false) @Temporal(TemporalType.DATE) private Date createdDate; @Column(name="created_by",nullable = false) private String createdBy; //onetoMany association @OneToMany(targetEntity = Comment.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name="post_id") private List comments = new ArrayList<>(); public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public void setComments(List comments) { this.comments = comments; } public List getComments() { return comments; } @Override public String toString() { return "Post [postId=" + postId + ", postTitle=" + postTitle + ", createdDate=" + createdDate + ", createdBy="+ createdBy + "]"; } } Comment.java ============ package com.ashokit.entity; import java.util.Date; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; @Entity @Table(name="ashokit_comments") public class Comment { @Id @Column(name = "comment_id") @GeneratedValue(strategy = GenerationType.AUTO) private int commentId; @Column(name="comment_info", nullable = false) private String commentInfo; @Column(name="created_date",nullable = false) @Temporal(TemporalType.DATE) private Date createdDate; @Column(name="created_by",nullable = false) private String createdBy; //creating manyToOne Association @ManyToOne(targetEntity = Post.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="post_id") private Post post; public int getCommentId() { return commentId; } public void setCommentId(int commentId) { this.commentId = commentId; } public String getCommentInfo() { return commentInfo; } public void setCommentInfo(String commentInfo) { this.commentInfo = commentInfo; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } @Override public String toString() { return "Comment [commentId=" + commentId + ", commentInfo=" + commentInfo + ", createdDate=" + createdDate + ", createdBy=" + createdBy + "]"; } } PostDao.java ============ package com.ashokit.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.ashokit.entity.Post; public interface PostDao extends JpaRepository{ } CommentDao.java =============== package com.ashokit.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.ashokit.entity.Comment; public interface CommentDao extends JpaRepository{ } Application.java ================ package com.ashokit; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.ashokit.dao.CommentDao; import com.ashokit.dao.PostDao; import com.ashokit.entity.Comment; import com.ashokit.entity.Post; @SpringBootApplication public class Application implements CommandLineRunner{ @Autowired private PostDao postDao; @Autowired private CommentDao commentDao; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { //First Post Information /*Post post = new Post(); post.setPostTitle("Spring Boot Post"); post.setCreatedDate(new Date()); post.setCreatedBy("Mahesh"); //Binding the First comment for First Post Comment firstComment = new Comment(); firstComment.setCommentInfo("Informative Session"); firstComment.setCreatedDate(new Date()); firstComment.setCreatedBy("Suresh"); //Binding the Second comment for First Post Comment secondComment = new Comment(); secondComment.setCommentInfo("Good Session"); secondComment.setCreatedDate(new Date()); secondComment.setCreatedBy("Ramesh"); //parent to child saving records post.setComments(List.of(firstComment,secondComment)); //saving the parent object Post postInfo = postDao.save(post); System.out.println("Post Information::::" + postInfo); //Second Post Information Post post1 = new Post(); post1.setPostTitle("Devops With AWS Post"); post1.setCreatedDate(new Date()); post1.setCreatedBy("Ashok"); //Binding the First comment for Second Post Comment firstPostComment = new Comment(); firstPostComment.setCommentInfo("Informative Session"); firstPostComment.setCreatedDate(new Date()); firstPostComment.setCreatedBy("Suresh"); //Binding the First comment for Second Post Comment secondPostComment = new Comment(); secondPostComment.setCommentInfo("Good Session"); secondPostComment.setCreatedDate(new Date()); secondPostComment.setCreatedBy("Ashok"); //Binding the First comment for Second Post Comment thirdPostComment = new Comment(); thirdPostComment.setCommentInfo("Good Informative Session"); thirdPostComment.setCreatedDate(new Date()); thirdPostComment.setCreatedBy("Ashok"); //setting parent to child object post1.setComments(List.of(firstPostComment,secondPostComment,thirdPostComment)); Post savedFirstPostInfo = postDao.save(post1); System.out.println("Saved First Post Info ::::::" + savedFirstPostInfo);*/ //Post To Comment Navigation /*Optional postInfo = postDao.findById(1); if(postInfo.isPresent()) { Post postData = postInfo.get(); System.out.println(postData); postData.getComments().forEach(eachComment -> System.out.println(eachComment)); }*/ //Comment To Post Navigation Optional commentInfo = commentDao.findById(1); if(commentInfo.isPresent()) { Comment commentData = commentInfo.get(); System.out.println(commentData); Post commentRelatedPost = commentData.getPost(); System.out.println(commentRelatedPost); } } } OneToMany Association with using mappedBy ========================================== Post.java ======== package com.ashokit.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; @Entity @Table(name="ashokit_posts") public class Post { @Id @Column(name = "post_id") @GeneratedValue(strategy = GenerationType.AUTO) private int postId; @Column(name="post_title", nullable = false) private String postTitle; @Column(name="created_date",nullable = false) @Temporal(TemporalType.DATE) private Date createdDate; @Column(name="created_by",nullable = false) private String createdBy; //onetoMany association /*@OneToMany(targetEntity = Comment.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name="post_id")*/ @OneToMany(targetEntity = Comment.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "post") private List comments = new ArrayList<>(); public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public String getPostTitle() { return postTitle; } public void setPostTitle(String postTitle) { this.postTitle = postTitle; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public void setComments(List comments) { this.comments = comments; } public List getComments() { return comments; } @Override public String toString() { return "Post [postId=" + postId + ", postTitle=" + postTitle + ", createdDate=" + createdDate + ", createdBy="+ createdBy + "]"; } } Comment.java ============ package com.ashokit.entity; import java.util.Date; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import jakarta.persistence.Temporal; import jakarta.persistence.TemporalType; @Entity @Table(name="ashokit_comments") public class Comment { @Id @Column(name = "comment_id") @GeneratedValue(strategy = GenerationType.AUTO) private int commentId; @Column(name="comment_info", nullable = false) private String commentInfo; @Column(name="created_date",nullable = false) @Temporal(TemporalType.DATE) private Date createdDate; @Column(name="created_by",nullable = false) private String createdBy; //creating manyToOne Association @ManyToOne(targetEntity = Post.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="post_id") private Post post; public int getCommentId() { return commentId; } public void setCommentId(int commentId) { this.commentId = commentId; } public String getCommentInfo() { return commentInfo; } public void setCommentInfo(String commentInfo) { this.commentInfo = commentInfo; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } @Override public String toString() { return "Comment [commentId=" + commentId + ", commentInfo=" + commentInfo + ", createdDate=" + createdDate + ", createdBy=" + createdBy + "]"; } } Application.java ================ package com.ashokit; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.ashokit.dao.CommentDao; import com.ashokit.dao.PostDao; import com.ashokit.entity.Comment; import com.ashokit.entity.Post; @SpringBootApplication public class Application implements CommandLineRunner{ @Autowired private PostDao postDao; @Autowired private CommentDao commentDao; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... args) throws Exception { //First Post Information Post post = new Post(); post.setPostTitle("Spring Boot Post"); post.setCreatedDate(new Date()); post.setCreatedBy("Mahesh"); //Binding the First comment for First Post Comment firstComment = new Comment(); firstComment.setCommentInfo("Informative Session"); firstComment.setCreatedDate(new Date()); firstComment.setCreatedBy("Suresh"); firstComment.setPost(post); //mappedBy attribute //Binding the Second comment for First Post Comment secondComment = new Comment(); secondComment.setCommentInfo("Good Session"); secondComment.setCreatedDate(new Date()); secondComment.setCreatedBy("Ramesh"); secondComment.setPost(post);//mappedBy attribute //parent to child saving records post.setComments(List.of(firstComment,secondComment)); //saving the parent object Post postInfo = postDao.save(post); System.out.println("Post Information::::" + postInfo); //Second Post Information Post post1 = new Post(); post1.setPostTitle("Devops With AWS Post"); post1.setCreatedDate(new Date()); post1.setCreatedBy("Ashok"); //Binding the First comment for Second Post Comment firstPostComment = new Comment(); firstPostComment.setCommentInfo("Informative Session"); firstPostComment.setCreatedDate(new Date()); firstPostComment.setCreatedBy("Suresh"); firstPostComment.setPost(post1); //mappedBy attribute //Binding the First comment for Second Post Comment secondPostComment = new Comment(); secondPostComment.setCommentInfo("Good Session"); secondPostComment.setCreatedDate(new Date()); secondPostComment.setCreatedBy("Ashok"); secondPostComment.setPost(post1); //mappedBy attribute //Binding the First comment for Second Post Comment thirdPostComment = new Comment(); thirdPostComment.setCommentInfo("Good Informative Session"); thirdPostComment.setCreatedDate(new Date()); thirdPostComment.setCreatedBy("Ashok"); thirdPostComment.setPost(post1); //mappedBy attribute //setting parent to child object post1.setComments(List.of(firstPostComment,secondPostComment,thirdPostComment)); Post savedFirstPostInfo = postDao.save(post1); System.out.println("Saved First Post Info ::::::" + savedFirstPostInfo); //Post To Comment Navigation /*Optional postInfo = postDao.findById(1); if(postInfo.isPresent()) { Post postData = postInfo.get(); System.out.println(postData); postData.getComments().forEach(eachComment -> System.out.println(eachComment)); }*/ //Comment To Post Navigation /*Optional commentInfo = commentDao.findById(1); if(commentInfo.isPresent()) { Comment commentData = commentInfo.get(); System.out.println(commentData); Post commentRelatedPost = commentData.getPost(); System.out.println(commentRelatedPost); }*/ } } Assignment ========== * @ManyToMany Association +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++