Spring Boot One-to-Many and Many-to-One Mapping

  • 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 User and Post Entities

We'll create a bidirectional One-to-Many relationship between User and 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<Post> 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<Post> getPosts() {
return posts;
}

public void setPosts(List<Post> posts) {
this.posts = posts;
}
}

@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).

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 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

Create JPA Repositories

UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}
PostRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface PostRepository extends JpaRepository<Post, Long> {
}

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<User> getUsersWithPosts() {
return userRepository.findAll();
}

// Get User by ID
public Optional<User> 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> 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<Post> 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<User> getUsers() {
return userService.getUsersWithPosts();
}

// Get User by ID
@GetMapping("/{id}")
public Optional<User> 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<Post> 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}

Delete Posts http://localhost:8080/posts/{postID}


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.