Spring Boot + JPA/Hibernate One to Many mapping example

Hello everyone, In this tutorial, we will learn how to implement one-to-many entity mapping using JPA/Hibernate with Spring Boot, Spring Data JPA, and the 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_onetomanymapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_jpa_hibernate_onetomanymapping</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:knfdb
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
spring.h2.console.enabled=true
Spring Boot will automatically configure a DataSource bean after reading the above properties. Don't forget to change the properties to match your MySQL or Postgresql or any database installation.


Create Entities

'one-to-many' relationship refers to the relationship between two entities/tables Employee and EmployeeContact in which one element/row of Employee may only be linked to many elements/rows of EmployeeContact, but a member of EmployeeContact is linked to only one element/row of Employee   The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Id annotation specifies the primary key of an entity and the @GeneratedValue provides for the specification of generation strategies for the values of primary keys. The @Column annotation is used to specify the mapped column for a persistent property or field. If no Column annotation is specified, the default value will be applied.

Employee.java

package com.example.demo.model;

import java.util.Set;
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.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "name")
private String name;
private Integer salary;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "empId")
private Set<EmployeeContact> employeeContacts;

public Set<EmployeeContact> getEmployeeContacts() {
return employeeContacts;
}

public void setEmployeeContacts(Set<EmployeeContact> employeeContacts) {
this.employeeContacts = employeeContacts;
}

public Employee() {
}

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 + ", employeeContacts=" + employeeContacts
+ "]";
}
}


EmployeeContact.java

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.java]

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);

}
@Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.


Controller[HomeController.java]

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";
}
}
}
The @RestController annotation was introduced in Spring 4.0 to simplify the engendering of RESTful web services. It's a convenience annotation that combines @Controller and @ResponseBody. @RequestMapping annotation maps HTTP requests to handler methods of MVC and REST controllers.


Main Driver Class

package com.example.demo;

import java.util.HashSet;
import java.util.Set;
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 contact1 = new EmployeeContact();
contact1.setPhoneNo(111111111111l);
EmployeeContact contact2 = new EmployeeContact();
contact2.setPhoneNo(22222222222222l);
Set<EmployeeContact> contacts = new HashSet<>();
contacts.add(contact1);
contacts.add(contact2);
employee.setEmployeeContacts(contacts);
employeeRepository.save(employee);

}
}
The @SpringBootApplication annotation is a convenience annotation that combines the @EnableAutoConfiguration, @Configuration and the @ComponentScan annotations.


Run & Test 

Github repository download link is provided at the end of this tutorial

Local Setup:

Step 1: Download or clone the source code to a local machine.

Step 2mvn clean install

Step 3: Run the Spring Boot application
mvn spring-boot:run


Add New Employee



Fetch All Employee


Delete Employee By Id


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete