We can think about the user and it's corresponding user_office_profile.
Each user will have only one office_profile for his unique identification.
- Open http://start.spring.io
- Click on Switch to Full Version
- Enter Artifact as “com.gaurav”
- Change Package Name to “springboot.hibernate.mapping”
- Select Web, Dev Tools, JPA and Mysql dependencies.
- Click Generate Project to generate and download the project.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gaurav</groupId>
<artifactId>springboot.hibernate.mapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot.hibernate.mapping</name>
<description>Demo project for Spring Boot and Hibernate mappings</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=9595
# MySQL settings
spring.datasource.url=jdbc:mysql://localhost:3306/experiment
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver.class=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug
Model Class
User.java
package com.gaurav.springboot.hibernate.mapping.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.Size;
@Entity
@Table(name = "users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(unique = true)
private String email;
@Size(max = 128)
private String password;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user")
private UserOfficeProfile userOfficeProfile;
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;
}
public UserOfficeProfile getUserOfficeProfile() {
return userOfficeProfile;
}
public void setUserOfficeProfile(UserOfficeProfile userOfficeProfile) {
this.userOfficeProfile = userOfficeProfile;
}
}
UserOfficeProfile.java
package com.gaurav.springboot.hibernate.mapping.model;
import java.io.Serializable;
import java.util.Date;
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.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "user_office_profile")
public class UserOfficeProfile implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "phone_number")
private String phoneNumber;
private String gender;
@Temporal(TemporalType.DATE)
@Column(name = "dob")
private Date dateOfBirth;
private String address;
private String street;
private String city;
private String state;
private String country;
@Column(name = "zip_code")
private String zipCode;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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;
}
}
UserRepository.java
package com.gaurav.springboot.hibernate.mapping.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.gaurav.springboot.hibernate.mapping.model.User;
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
UserOfficeProfileRepository.java
package com.gaurav.springboot.hibernate.mapping.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.gaurav.springboot.hibernate.mapping.model.UserOfficeProfile;
@Repository
public interface UserOfficeProfileRepository extends CrudRepository<UserOfficeProfile, Long> {
}
HibernateOneToOneDemoApplication.java
package com.gaurav.springboot.hibernate.mapping;
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 com.gaurav.springboot.hibernate.mapping.model.User;
import com.gaurav.springboot.hibernate.mapping.model.UserOfficeProfile;
import com.gaurav.springboot.hibernate.mapping.repository.UserOfficeProfileRepository;
import com.gaurav.springboot.hibernate.mapping.repository.UserRepository;
@SpringBootApplication
public class HibernateOneToOneDemoApplication implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private UserOfficeProfileRepository userOfficeProfileRepository;
public static void main(String[] args) {
SpringApplication.run(HibernateOneToOneDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// Removing all the child records from existing database.
userOfficeProfileRepository.deleteAll();
// Removing all the parent records from existing database.
userRepository.deleteAll();
// Creating Parent Object instance
User user = new User();
user.setFirstName("Gaurav");
user.setLastName("kumar");
user.setEmail("gaurav@gmail.com");
user.setPassword("TEST_PASSWORD");
Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set(1985, 11, 28);
// Creating a Child Object instance
UserOfficeProfile userOfficeProfile = new UserOfficeProfile();
userOfficeProfile.setPhoneNumber("+91-8901236547");
userOfficeProfile.setGender("Male");
userOfficeProfile.setDateOfBirth(dateOfBirth.getTime());
userOfficeProfile.setAddress("31 SC");
userOfficeProfile.setStreet("X Road");
userOfficeProfile.setCity("HYDERABAD");
userOfficeProfile.setState("Telangana");
userOfficeProfile.setCountry("India");
userOfficeProfile.setZipCode("500123");
// placing child reference with respect to parent entity(user)
user.setUserOfficeProfile(userOfficeProfile);
// placing parent reference with respect to child
// entity(userOfficeProfile)
userOfficeProfile.setUser(user);
// Saving Parent Reference (which will save the child also)
userRepository.save(user);
}
}
Table schema
CREATE TABLE users (id BIGINT NOT NULL AUTO_INCREMENT,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(65) NOT NULL,
last_name VARCHAR(65),
PASSWORD VARCHAR(128) NOT NULL,
PRIMARY KEY (id))
CREATE TABLE user_office_profile (id BIGINT NOT NULL AUTO_INCREMENT, address VARCHAR(255), city VARCHAR(255), country VARCHAR(255), dob DATE, gender VARCHAR(255),
phone_number VARCHAR(255),
state VARCHAR(255),
street VARCHAR(255),
zip_code VARCHAR(255),
user_id BIGINT NOT NULL, PRIMARY KEY (id))
OUTPUT
2018-06-16 18:17:24 INFO o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 9595 (http) with context path ''
2018-06-16 18:17:24 INFO c.g.s.h.m.HibernateOneToOneDemoApplication - Started HibernateOneToOneDemoApplication in 5.177 seconds (JVM running for 6.037)
2018-06-16 18:17:24 INFO o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - delete from user_office_profile
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - delete from users
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - insert into users (email, first_name, last_name, password) values (?, ?, ?, ?)
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - insert into user_office_profile (address, city, country, dob, gender, phone_number, state, street, user_id, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)