Basic Tutorial
Queries
✅ A User can have multiple Posts
✅ A Post belongs to only one User
User
and Post
EntitiesWe'll create a bidirectional One-to-Many relationship between User
and Post
.
✅ @OneToMany(mappedBy = "user")
→ Specifies that User
is the parent.
✅ cascade = CascadeType.ALL
→ Ensures changes in User
reflect in Post
.
✅ orphanRemoval = true
→ Automatically deletes orphaned Post
entries when removed from User
.
✅ @JsonManagedReference
→ This marks the owning side (parent).
✅ @ManyToOne
→ Defines that Post
belongs to a User
.
✅ @JoinColumn(name = "user_id")
→ Creates a foreign key user_id
in the Post
table.
✅ @JsonBackReference
→ This marks the child side, preventing it from serializing the User
field.
Table name : user
id | name |
---|
Table name : post
id | title | user_id |
---|
Once the application is running, test the endpoints:
http://localhost:8080/users
http://localhost:8080/users
http://localhost:8080/users/{userID}
http://localhost:8080/users
http://localhost:8080/users/{userID}
Once the application is running, test the endpoints:
http://localhost:8080/posts/{userID}
http://localhost:8080/posts/{userID}
http://localhost:8080/posts/{postID}