Creating Post Entity and Many to One Relationship with User Entity

In this section, we will create a Post entity that contains many to one relationship with the User entity.

Step 1: Create a class with the name Post.java in the package com.javatpoint.server.main.user.

Step 2: Post.java is an entity, so we need to add @Entity annotation.

Step 3: Add three fields: id, description, and user.

Step 4: Generate Getters and Setters.

Step 5: Generate toString().

Remember: Uncheck the user during the generation of toString().

Step 6: A user can do many posts, so add @ManyToOne annotation. The User entity has many to one relationship with the Post entity. The fetch type will not retrieve the details of the user unless we called Post.getUser.

Step 7: Id is a primary key, so we need to add @Id annotation.

Post.java

We have configured the relationship on the side of Post entity. Now we are required to configure relationship on the side of User entity.

A user can make a list of posts, so the post has one-to-many relationships.

Step 8: Open User.java file and create a list of posts.

Step 9: Add an annotation @OneToMany with property (mappedBy="user"). It will create a relationship column in the Post entity.

Step 10: Generate Getters and Setters.

User.java

Step 11: Restart the application.

Creating Post Entity and Many to One Relationship with User Entity

We can see in the log that there are two tables post and user. The Post table has a link to the User table by a user id. A user can have multiple posts, and all of them have the same user id.

Step 12: Now, open the H2 Console. We can see that are two tables named USER and POST.

Creating Post Entity and Many to One Relationship with User Entity

Step 13: Open the data.sql file that we have created earlier and insert the data into POST table. We have inserted the following data:

data.sql

Step 14: Restart the application.

Step 15: Restart the H2 Console and execute the query SELECT *FROM POST;

It shows the data which we have inserted into the data.sql file.

Creating Post Entity and Many to One Relationship with User Entity






Latest Courses