Skip to main content

One to One Mapping with Spring boot

In this blog, I will explain how to use one-to-one mapping in Spring boot Application

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

Popular posts from this blog

Java Increment Operations: `n++` vs `n = n + 1` vs `n += 1`

In Java, incrementing a variable by one can be done in several ways: n++ , n = n + 1 , and n += 1 . While these expressions achieve the same end result, they differ slightly in syntax and use cases. Let's explore each one and discuss their performance. 1. n++ Post-Increment Operator : Increments the value of n by 1 after its current value has been used. Common Usage : Typically used in loops and other contexts where the current value needs to be used before incrementing. int n = 5; n++; // n is now 6 2. n = n + 1 Addition Assignment : Explicitly sets n to its current value plus 1. Readability : Straightforward and clear, though slightly more verbose. int n = 5; n = n + 1; // n is now 6 3. n += 1 Compound Assignment Operator : Equivalent to n = n + 1 , but more concise. Usage : Combines addition and assignment into one step. int n = 5; n += 1; // n is

Understanding C1 and C2 Compilers in Java

Understanding C1 and C2 Compilers in Java Understanding C1 and C2 Compilers in Java In Java, the Just-In-Time (JIT) compiler is a part of the Java Virtual Machine (JVM) that improves the performance of Java applications by compiling bytecode into native machine code at runtime. The JIT compiler includes two different compilers, known as the C1 and C2 compilers, each with distinct optimization strategies and purposes. C1 Compiler (Client Compiler) The C1 compiler, also known as the client compiler, is designed for fast startup times and lower memory consumption. It performs lighter and quicker optimizations, which makes it suitable for applications that require quick startup and responsiveness. Key characteristics of the C1 compiler include: Quick Compilation: Prioritizes fast compilation times over deep optimizations. Low Overhead: Consumes less memory and resources during compilation. Profile-Guided Optimization: Ca

When To Use Indexes In MySQL

When deciding when and how to create an index in your MySQL database, it's important to consider how the data is being used. Let's say you have a database of  students . We will create it like this: CREATE TABLE `students` ( `id` int ( 11 ) NOT NULL AUTO_INCREMENT , `first_name` varchar ( 255 ) DEFAULT NULL , `last_name` varchar ( 255 ) DEFAULT NULL , `class` varchar ( 255 ) DEFAULT NULL , PRIMARY KEY ( `id` ) ) ENGINE = InnoDB Indexes are best used on columns that are frequently used in where clauses, and in any kind of sorting, such as "order by". You should also pay attention to whether or not this information will change frequently, because it will slow down your updates and inserts. Since you wont frequently be adding students, you don't have to worry about the inserts Let's say that you will be looking up the students with a web interface and the end user will be typing in the students name to find them, since r