0
0
Spring Bootframework~30 mins

@OneToOne relationship in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a @OneToOne Relationship in Spring Boot
📖 Scenario: You are building a simple Spring Boot application to manage users and their profiles. Each user has exactly one profile, and each profile belongs to exactly one user.
🎯 Goal: Build two entity classes User and UserProfile with a @OneToOne relationship between them using Spring Boot and JPA annotations.
📋 What You'll Learn
Create a User entity with fields id and username
Create a UserProfile entity with fields id and bio
Add a @OneToOne relationship from User to UserProfile
Use @JoinColumn to specify the foreign key column in User
Ensure the code compiles and follows Spring Boot JPA entity conventions
💡 Why This Matters
🌍 Real World
One-to-one relationships are common in applications where two entities have a direct and exclusive link, such as a user and their profile, or a person and their passport.
💼 Career
Understanding how to model and implement @OneToOne relationships is essential for backend developers working with Spring Boot and JPA to build relational data models.
Progress0 / 4 steps
1
Create the User entity
Create a class called User annotated with @Entity. Add private fields Long id annotated with @Id and @GeneratedValue, and String username. Add public getters and setters for both fields.
Spring Boot
Need a hint?

Use @Entity on the class. Use @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) on the id field.

2
Create the UserProfile entity
Create a class called UserProfile annotated with @Entity. Add private fields Long id annotated with @Id and @GeneratedValue, and String bio. Add public getters and setters for both fields.
Spring Boot
Need a hint?

Use @Entity on the class. Use @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) on the id field.

3
Add @OneToOne relationship in User
In the User class, add a private field UserProfile profile annotated with @OneToOne and @JoinColumn(name = "profile_id"). Add public getter and setter for profile.
Spring Boot
Need a hint?

Use @OneToOne and @JoinColumn(name = "profile_id") on the profile field in User.

4
Complete the @OneToOne relationship setup
Ensure both User and UserProfile classes are in the same package and properly imported. Add @Entity annotations and all necessary imports. Confirm the code compiles without errors.
Spring Boot
Need a hint?

Make sure all imports and annotations are present and both classes are complete.