Spring Boot + JPA/Hibernate One to One mapping example

Hello everyone,In this tutorial, we will learn how to implement  one-to-one entity mapping using JPA/Hibernate with Spring Boot, Spring Data JPA, and H2DB database.



Project Structure 

See the final project structure of this tutorial.




Maven[pom.xml] 

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project. It contains default values for most projects. Some of the configurations that can be designated in the POM is the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists, and such can withal be designated.

<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot_jpa_hibernate_onetoonemapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_jpa_hibernate_onetoonemapping</name>
<description>Demo project for Spring Boot</description>

<properties>
<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>com.h2database</groupId>
<artifactId>h2</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

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE


Modal class[Employee.class]

package com.example.demo.model;

import javax.persistence.*;

@Entity
@Table(name = "employees")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "employeeId")
private Integer id;
@Column(name = "name")
private String name;
private Integer salary;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "id")
private EmployeeContact employeeContact;

public Employee() {
}

public EmployeeContact getEmployeeContact() {
return employeeContact;
}

public void setEmployeeContact(EmployeeContact employeeContact) {
this.employeeContact = employeeContact;
}

public Integer getId() {
return id;
}

public Employee setId(Integer id) {
this.id = id;
return this;
}

public String getName() {
return name;
}

public Employee setName(String name) {
this.name = name;
return this;
}

public Integer getSalary() {
return salary;
}

public Employee setSalary(Integer salary) {
this.salary = salary;
return this;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", salary="
+ salary + ", employeeContact=" + employeeContact
+ "]";
}

}


Model class[EmployeeContact.class]

package com.example.demo.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee_contact")
public class EmployeeContact {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
private Long phoneNo;

public EmployeeContact() {
}

public Integer getId() {
return id;
}

public EmployeeContact setId(Integer id) {
this.id = id;
return this;
}

public Long getPhoneNo() {
return phoneNo;
}

public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}

@Override
public String toString() {
return "EmployeeContact [id=" + id + ", phoneNo=" + phoneNo + "]";
}

}


Repository[EmployeeRepository.class]

package com.example.demo.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.model.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
List<Employee> findByName(String name);

}


Controller[HomeController.class]

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;

@RestController
@RequestMapping("employee")
public class HomeController {
@Autowired
EmployeeRepository employeeRepository;

@GetMapping
public List<Employee> findAll() {
return employeeRepository.findAll();

}

@PostMapping
public Employee saveEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);

}

@GetMapping("/{employeeName}")
public List<Employee> findByName(@PathVariable("employeeName")
String employeeName) {
return employeeRepository.findByName(employeeName);

}

@DeleteMapping("/{id}")
public String deleteEmployee(@PathVariable("id") Integer id) {
try {
employeeRepository.deleteById(id);
return "Deleted successfully";
} catch (Exception e) {
return "Failed to delete";
}
}
}


Main Driver Class[SpringbootJpaHibernateOnetoonemappingApplication.class]

package com.example.demo;

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.example.demo.model.Employee;
import com.example.demo.model.EmployeeContact;
import com.example.demo.repository.EmployeeRepository;

@SpringBootApplication
public class SpringbootJpaHibernateOnetoonemappingApplication
implements CommandLineRunner {
@Autowired
EmployeeRepository employeeRepository;

public static void main(String[] args) {
SpringApplication.run
(SpringbootJpaHibernateOnetoonemappingApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
Employee employee = new Employee();
employee.setName("sibin");
employee.setSalary(12500);
EmployeeContact contact = new EmployeeContact();
contact.setPhoneNo(111111111111l);
employee.setEmployeeContact(contact);
employeeRepository.save(employee);

}

}


Run & Test 

Run Spring Boot application with the command: mvn spring-boot:run


Add New Employee




Fetch All Employee




Delete Employee By Id




Comments