A One-to-Many relationship means one entity is related to multiple entities.
A Many-to-One relationship means multiple child entities are related to a single parent entity.
Example:
✅ A User can have multiple Posts
✅ A Post belongs to only one User
Define Userand PostEntities
We'll create a bidirectional One-to-Many relationship between Userand Post.
User.java
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import java.util.List;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference // 🔥 Prevents infinite recursion
private List posts;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getPosts() {
return posts;
}
public void setPosts(List posts) {
this.posts = posts;
}
}
✅ @OneToMany(mappedBy = "user") → Specifies that Useris the parent.
✅ cascade = CascadeType.ALL → Ensures changes in Userreflect in Post.
✅ orphanRemoval = true → Automatically deletes orphaned Postentries when removed from User.
✅ @JsonManagedReference → This marks the owning side (parent).
Post.java
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
@Entity
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
@JsonBackReference // 🔥 Prevents infinite recursion
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
✅@ManyToOne → Defines that Postbelongs to a User.
✅ @JoinColumn(name = "user_id") → Creates a foreign key user_idin the Posttable.
✅ @JsonBackReference → This marks the child side, preventing it from serializing the Userfield.
Table name : user
id
name
Table name : post
id
title
user_id
Create JPA Repositories
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository {
}
PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository {
}
Create Services
UserService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PostRepository postRepository;
// Create User with Posts
public User createUserWithPosts(User user) {
if (user.getPosts() != null) {
for (Post post : user.getPosts()) {
post.setUser(user); // 🔥 Automatically assign user to posts
}
};
return userRepository.save(user);
}
// Get Users
public List getUsersWithPosts() {
return userRepository.findAll();
}
// Get User by ID
public Optional getUserById(Long id) {
return userRepository.findById(id);
}
// Update User
public User updateUser(User user) {
return userRepository.save(user);
}
// Delete User (Cascade deletes Posts)
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
PostService.java
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
private final PostRepository postRepository;
private final UserRepository userRepository;
public PostService(PostRepository postRepository, UserRepository userRepository) {
this.postRepository = postRepository;
this.userRepository = userRepository;
}
// Create Post for a specific User
public Post createPost(Long userId, Post post) {
Optional user = userRepository.findById(userId);
if (user.isPresent()) {
post.setUser(user.get());
return postRepository.save(post);
} else {
throw new RuntimeException("User not found!");
}
}
// Get Posts by User ID
public List getPostsByUser(Long userId) {
return postRepository.findAll().stream()
.filter(post -> post.getUser().getId().equals(userId))
.toList();
}
// Delete Post by ID
public void deletePost(Long postId) {
postRepository.deleteById(postId);
}
}
Create Controllers
UserController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// Create User with Posts
@PostMapping
public User createUser(@RequestBody User user) {
return userService.createUserWithPosts(user);
}
// Create User with Posts
@GetMapping
public List getUsers() {
return userService.getUsersWithPosts();
}
// Get User by ID
@GetMapping("/{id}")
public Optional getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
// Get User by ID
@PutMapping
public User updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
// Delete User (Cascade deletes Posts)
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "Deleted Successfully";
}
}
PostController.java
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/posts")
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
// Create Post for a User
@PostMapping("/{userId}")
public Post createPost(@PathVariable Long userId, @RequestBody Post post) {
return postService.createPost(userId, post);
}
// Get Posts by User ID
@GetMapping("/user/{userId}")
public List getPostsByUser(@PathVariable Long userId) {
return postService.getPostsByUser(userId);
}
// Delete Post by ID
@DeleteMapping("/{postId}")
public void deletePost(@PathVariable Long postId) {
postService.deletePost(postId);
}
}
Testing the REST API with Postman for one-to-many:
Once the application is running, test the endpoints:
Create User http://localhost:8080/users
Get All Users http://localhost:8080/users
Get User By Id http://localhost:8080/users/{userID}
Update User http://localhost:8080/users
Delete User http://localhost:8080/users/{userID}
Testing the REST API with Postman for many-to-one:
Once the application is running, test the endpoints:
Create Post http://localhost:8080/posts/{userID}
Get Posts by user id http://localhost:8080/posts/{userID}
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.