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

A 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.

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

}

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";
}
}

}

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

}

}

Run & Test 

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


Add New Employee



Fetch All Employee


Delete Employee By Id



More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Spring boot video streaming example-HTML5

Spring Boot + OpenCSV Export Data to CSV Example

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring boot web project free download:User Registration System

10 Best Job Posting Sites 2021-2022

5 Hardest Puzzle,100% fail answers

ReactJS - Bootstrap - Buttons

Spring Boot-AngularJS-Bootstrap-JPA-CRUD

Java security AES,SHA256,SHA512,MD5-Spring Boot Project Free Download