Implementing One to One Mapping in Spring Boot using JPA
Posted By : Shanu Kumar | 30-Apr-2018
In this blog, I am going to continue my mapping series with entities in spring boot.
You can also check my last two blogs One_to_Many mapping and Many To Many mapping
Today, I am going to write One-to-One mapping relationship using JPA.
Consider the following tables, USER and USER_PROFILES.in User table, it makes sense to store user primary
details and store all the secondary
Creating the Project
--> Using Spring Initializr web tool
Here we are going to generate the project from Spring Initializr web tool.
1. Go to http://start.spring.io
2. Click Switch to full version link to see all the options
3. Enter Artifact as “demo”
4. Change Package Name to “com.example.app”
6. Click Generate Project to download the project.
Database and Logging Configuration
application.properties.
in this file, we configure our
development environment configuration. we find out
server.port=9090
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.datasource.url= jdbc:mysql://localhost:3306/one_to_one?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hibernate
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
9090 is default port to run the application and Scheme name is one_to_one.
Let's create our required Domain.
Domain Models
For this, we create a package name with the model inside com.example.app.model and create the following classes inside this package.
1. User model
package com.example.app.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;
import java.io.Serializable;
@Entity
@Table(name = "users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Email
@Column(unique = true)
private String email;
@NotNull
@Size(max = 10)
private String password;
@OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;
public User() {
}
public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
// Getters and Setters (Omitted for brevity)
}
2. Gender Enum
we are creating Enum class for to store the Gender of User inside com.example.app.model
Gender.java.
package com.example.app.model;
public enum Gender {
MALE,
FEMALE
}
3. UserProfile model
create UserProfile.java inside com.example.app.model package
package com.example.app.model;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
@Entity
@Table(name = "user_profiles")
public class UserProfile implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "phone_number")
@Size(max = 15)
private String phoneNumber;
@Enumerated(EnumType.STRING)
@Column(length = 10)
private Gender gender;
@Temporal(TemporalType.DATE)
@Column(name = "dob")
private Date dateOfBirth;
@Size(max = 100)
private String address1;
@Size(max = 100)
private String address2;
@Size(max = 100)
private String street;
@Size(max = 100)
private String city;
@Size(max = 100)
private String state;
@Size(max = 100)
private String country;
@Column(name = "zip_code")
@Size(max = 32)
private String zipCode;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
public UserProfile() {
}
public UserProfile(String phoneNumber, Gender gender, Date dateOfBirth,
String address1, String address2, String street, String city,
String state, String country, String zipCode) {
this.phoneNumber = phoneNumber;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.address1 = address1;
this.address2 = address2;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}
// Getters and Setters (Omitted for brevity)
}
we specify @OneToOne annotation in both mode but one entity is the
the owner of this relationship contains @JoinColumn annotation to Foreign Key define
Defining Repositories
now we have to create a package name with repository inside com.example.app. and create the following interfaces inside this package.
1. UserRepository
package com.example.app.repository; import com.example.app.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User,Long>
{ }
2. UserProfileRepository
package com.example.app.repository;
import com.example.app.model.UserProfile;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserProfileRepository extends JpaRepository<UserProfile,Long>
{ } That's all we need to create repository.
Now,Open the main
DemoApplication.java
package com.example.app;
import com.example.app.model.User;
import com.example.jpa.model.Gender;
import com.example.app.model.UserProfile;
import com.example.app.repository.UserRepository;
import com.example.app.repository.UserProfileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import java.util.Calendar;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpaManyToManyDemoApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepo;
@Autowired
private UserProfileRepository userProfileRepo;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
User user = new User("Shanu", "Kumar", "[email protected]",
"nothing.1234");
Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set(1995, 12, 16);
UserProfile userProfile = new UserProfile("+91-8574857882", Gender.MALE, dateOfBirth.getTime(),
"345", "2nd street", "sohna road, Badsahpur", "Gurugram",
"Hariyana", "India", "122018");
user.setUserProfile(userProfile);
userProfile.setUser(user);
userRepo.save(user);
}
}
Now, time to Run Applcation.you can check you DB.
Hope so, You like this Article.
Thank you so much.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shanu Kumar
Shanu has experience in Java EE & Java SE and also interested in EJB application. He has knowledge of SQL and worked on MYSQL & Oracle databases. He loves listening to music.