In this blog, I will explain how to use one-to-one mapping in Spring boot Application
What you need?
What you need?
- JAVA
- MySql
- Eclipse IDE ( whatever you like IDE, I'm using Eclipse for this example)
- Maven ( you can use the Gradle as well)
Initial Plan
I will create a spring boot application project using the Spring Initializer web tool and import the project as a maven project. after configuring the all necessary setting, I will code for one-to-one mapping.
Below diagram is the database model diagram which we going to install using the spring boot application.
Let's Start to Code.
You need to configure the application.properties file for database connections. add the following content to the src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/learning
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = create
server.port=8081
Change the database username and password according to your MySql configurations.
Define Entities.
User Entity
package lk.harshana.demohibernate.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table(name = "USER")
public class User implements Serializable {
private static final long servialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(max=50)
@Column(name="first_name")
private String firstName;
@NotNull
@Size(max=50)
@Column(name="last_name")
private String lastName;
@NotNull
@Email
@Size(max = 100)
@Column(unique = true)
private String email;
@NotNull
@Size(max= 128)
private String password;
@OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
public User() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserProfile Entity
package lk.harshana.demohibernate.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
@Entity
@Table(name = "user_profile")
public class UserProfile implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Size(max = 13)
@Column(name = "phone_number")
private String phoneNumber;
@Enumerated(EnumType.STRING)
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 = 20)
private String state;
@Size(max = 20)
private String city;
@Size(max = 20)
private String street;
@Size(max = 20)
private String country;
@Size(max = 10)
private String zipCode;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
public UserProfile() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
For Gender property, Enum is used.
package lk.harshana.demohibernate.model;
public enum Gender {
MALE,
FEMALE
}
Defining the Repository
UserRepository
package lk.harshana.demohibernate.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import lk.harshana.demohibernate.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{}
UserProfileRepository
package lk.harshana.demohibernate.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import lk.harshana.demohibernate.model.UserProfile;
@Repository
public interface UserProfileRepository extends JpaRepository<UserProfile, Long>{}
Codes for testing one-to-one mapping
package lk.harshana.demohibernate;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import lk.harshana.demohibernate.model.Gender;
import lk.harshana.demohibernate.model.User;
import lk.harshana.demohibernate.model.UserProfile;
import lk.harshana.demohibernate.repository.UserProfileRepository;
import lk.harshana.demohibernate.repository.UserRepository;
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private UserProfileRepository userProfileRepository;
@Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
User user = new User();
user.setFirstName("Harshana");
user.setLastName("Madusanka");
user.setEmail("example@gmail.com");
user.setPassword("password");
Calendar dob = Calendar.getInstance();
dob.set(1989, 4, 9);
UserProfile userProfile = new UserProfile();
userProfile.setPhoneNumber("0112222222");
userProfile.setAddress1("Warakapola");
userProfile.setAddress2("colombo");
userProfile.setCity("Warakapola");
userProfile.setCountry("Sri Lanka");
userProfile.setDateOfBirth(dob.getTime());
userProfile.setGender(Gender.MALE);
userProfile.setState("Kegalle");
userProfile.setStreet("Dorawaka");
userProfile.setZipCode("7200");
user.setUserProfile(userProfile);
userProfile.setUser(user);
userRepository.save(user);
}
}
This is my project structure.
Okay, coding is done. now we need to test the application using the following command
mvn spring-boot:run
The application was run successfully. So let's check the database for application output
User Table
UserProfile Table
Comments
Post a Comment