Advertisement

Google Ad Slot: content-top

Spring Boot One-to-One Mapping

~1 min read · Spring Boot
On this page

A One-to-One relationship means one entity is associated with exactly one other entity.

Example:

A User has exactly one Profile

A Profile belongs to exactly one User


Define User and Profile Entities

We'll create a bidirectional relationship where both User and Profile reference each other.

User.java
import jakarta.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "profile_id", referencedColumnName = "id") private Profile profile; // 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 Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } }

@OneToOne(cascade = CascadeType.ALL) → Ensures changes in User also apply to Profile.

@JoinColumn(name = "profile_id") → Defines the foreign key column in the User table.

Profile.java
import jakarta.persistence.*; @Entity public class Profile { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String bio; private String phone; // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBio() { return bio; } public void setBio(String bio) { this.bio = bio; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }

Table name : profile

id bio phone

Table name : user

id name profile_id

Create JPA Repositories

UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { }
ProfileRepository.java
import org.springframework.data.jpa.repository.JpaRepository; public interface ProfileRepository extends JpaRepository { }

Create Services

UserService.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private ProfileRepository profileRepository; }
ProfileService.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ProfileService { @Autowired private ProfileRepository profileRepository; }

Create Controllers

ProfileController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/profiles") public class ProfileController { @Autowired private ProfileService profileService; }
UserController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; }

Create REST API Controller for Profile

ProfileController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/profiles") public class ProfileController { @Autowired private ProfileService profileService; // ✅ Create Profile @PostMapping public Profile addUser(@RequestBody Profile profile) { return profileService.saveProfile(profile); } // ✅ Get All Users @GetMapping public List getUsers() { return profileService.getAllProfiles(); } // ✅ Get Profile by ID @GetMapping("/{id}") public Profile getUser(@PathVariable Long id) { return profileService.getProfileById(id); } // ✅ Update Profile @PutMapping public Profile updateUser(@RequestBody Profile profile) { return profileService.updateProfile(profile); } // ✅ Delete Profile @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { return profileService.deleteProfile(id); } }
ProfileService.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class ProfileService { @Autowired private ProfileRepository profileRepository; // ✅ Create Profile public Profile saveProfile(Profile profile) { return profileRepository.save(profile); } // ✅ Get All Profiles public List getAllProfiles() { return profileRepository.findAll(); } // ✅ Get Profile by ID public Profile getProfileById(Long id) { return profileRepository.findById(id).orElse(null); } // ✅ Update Profile public Profile updateProfile(Profile profile) { return profileRepository.save(profile); } // ✅ Delete Profile public String deleteProfile(Long id) { profileRepository.deleteById(id); return "Profile deleted!"; } }
ProfileRepository.java
import org.springframework.data.jpa.repository.JpaRepository; public interface ProfileRepository extends JpaRepository { }

Testing the REST API with Postman:

Once the application is running, test the endpoints:


Create Profile http://localhost:8080/profiles


Get All Profiles http://localhost:8080/profiles

Get Profile By Id http://localhost:8080/profiles/{profileID}

Update Profile http://localhost:8080/profiles

Delete Profile http://localhost:8080/profiles/{profileID}


Create REST API Controller for User

UserController.java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; // ✅ Create User @PostMapping public User addUser(@RequestBody User user) { return userService.saveUser(user); } // ✅ Get All Users @GetMapping public List getUsers() { return userService.getAllUsers(); } // ✅ Get Userby id @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } // ✅ Update User @PutMapping public User updateUser(@RequestBody User user) { return userService.updateUser(user); } // ✅ Delete User By id @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { return userService.deleteUser(id); } // ✅ Create User connect with existing profile @PutMapping("/existingProfile/{profileId}") public User updateUserWithExistingProfile(@PathVariable Long profileId, @RequestBody User user) { return userService.createUserWithExistingProfile(profileId, user); } // ✅ Update User connect with existing profile @PutMapping("/existingUserProfile/{profileId}/{userId}") public User updateUserProfile(@PathVariable Long profileId, @PathVariable Long userId) { return userService.updateExistingUserProfile(profileId, userId); } // ✅ Update profile connected with user @PutMapping("/{userId}/profile/update-name") public User updateProfileName(@PathVariable Long userId, @RequestParam String newProfileName) { return userService.updateUserProfileName(userId, newProfileName); } // ✅ Delete profile connected with user set null in profile_id column @DeleteMapping("/{userId}/profile") public User removeProfile(@PathVariable Long userId) { return userService.removeUserProfile(userId); } }
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 ProfileRepository profileRepository; // ✅ Create User public User saveUser(User user) { return userRepository.save(user); } // ✅ Get All Users public List getAllUsers() { return userRepository.findAll(); } // ✅ Get User by id public User getUserById(Long id) { return userRepository.findById(id).orElse(null); } // ✅ Update User public User updateUser(User user) { return userRepository.save(user); } // ✅ Delete User By id public String deleteUser(Long id) { userRepository.deleteById(id); return "User deleted!"; } // ✅ Create User connect with existing profile public User createUserWithExistingProfile(Long profileId, User user) { if (profileId != null) { Optional existingProfile = profileRepository.findById(profileId); existingProfile.ifPresent(user::setProfile); } return userRepository.save(user); } // ✅ Update User connect with existing profile public User updateExistingUserProfile(Long profileId, Long userId) { if (profileId != null && userId != null) { Optional existingProfile = profileRepository.findById(profileId); Optional existingUser = userRepository.findById(userId); if (existingUser.isPresent() && existingProfile.isPresent()) { User user = existingUser.get(); user.setProfile(existingProfile.get()); return userRepository.save(user); } } return null; } // ✅ Update profile connected with user public User updateUserProfileName(Long userId, String newProfileName) { Optional existingUser = userRepository.findById(userId); if (existingUser.isPresent()) { User user = existingUser.get(); Profile profile = user.getProfile(); if (profile != null) { profile.setBio(newProfileName); // Update profile name (bio) profileRepository.save(profile); // Save updated profile return user; } else { throw new RuntimeException("Profile not found for User ID: " + userId); } } else { throw new RuntimeException("User not found with ID: " + userId); } } // ✅ Delete profile connected with user set null in profile_id column public User removeUserProfile(Long userId) { Optional existingUser = userRepository.findById(userId); if (existingUser.isPresent()) { User user = existingUser.get(); Profile profile = user.getProfile(); if (profile != null) { user.setProfile(null); // Remove profile from user userRepository.save(user); // Save updated user (profile detached) return user; } else { throw new RuntimeException("Profile not found for User ID: " + userId); } } else { throw new RuntimeException("User not found with ID: " + userId); } } }
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { }

Testing the REST API with Postman:

Once the application is running, test the endpoints:


Create User With Profile http://localhost:8080/users

Get All Users With Profile http://localhost:8080/users

Get Users With Profile by user id http://localhost:8080/users/{userID}

Update Users http://localhost:8080/users

Delete Users http://localhost:8080/users/{userID}

Create Users with existing profile id http://localhost:8080/users/existingProfile/{profileID}

Update Existing Users With Existing Profile http://localhost:8080/users/existingUserProfile/{profileID}/{userID}

Update Profile by Using User id http://localhost:8080/users/{userID}/profile/update-name?newProfileName=Mobile Developer

Delete Profile by Using User id http://localhost:8080/users/{userID}/profile