Spring Boot Crud Example Using One to Many Mapping


Hey guys in this post, we will discuss JPA One-to-Many Uni-directional mapping with Example. We will create a spring boot project step by step and connect it to the MySQL database. Follow this tutorial till the end to understand the JPA one-to-many uni-directional mapping. This is the continuation of the previous post, please follow that post before proceeding with this.

Complete example


Let's create a step-by-step spring boot project and create a bi-directional mapping between the two tables. We will create a mapping between Laptop and Color tables.

Read More:

  1. Check this how to write JPQL select query
  2. Check this how to write a JPQL delete query

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

            <?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.4.4</version> 		<relativePath/> <!-- lookup parent from repository --> 	</parent> 	<groupId>in.bushansirgur</groupId> 	<artifactId>findbyfieldname</artifactId> 	<version>v1</version> 	<name>findbyfieldname</name> 	<description>Spring boot data jpa find by field name</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>org.springframework.boot</groupId> 			<artifactId>spring-boot-devtools</artifactId> 			<scope>runtime</scope> 			<optional>true</optional> 		</dependency> 		<dependency> 			<groupId>mysql</groupId> 			<artifactId>mysql-connector-java</artifactId> 			<scope>runtime</scope> 		</dependency> 		<dependency> 			<groupId>org.projectlombok</groupId> 			<artifactId>lombok</artifactId> 			<optional>true</optional> 		</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> 				<configuration> 					<excludes> 						<exclude> 							<groupId>org.projectlombok</groupId> 							<artifactId>lombok</artifactId> 						</exclude> 					</excludes> 				</configuration> 			</plugin> 		</plugins> 	</build>  </project>                      

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container.

spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-data-jpa dependency is a starter for using Spring Data JPA with Hibernate. lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString()

Configure the datasource


            spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=scbushan05 spring.datasource.password=scbushan05  spring.jpa.hibernate.ddl-auto=update                      

Create an entity class


Create Color.java inside the in.bushansirgur.springboot.entity package and add the following content

            package in.bushansirgur.springboot.entity;  import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table;  import lombok.Getter; import lombok.Setter;  @Entity @Table(name = "tbl_colors") @Setter @Getter public class Color {  	@Id 	@GeneratedValue(strategy = GenerationType.IDENTITY) 	private Long id; 	 	private String color; 	 	@ManyToOne 	@JoinColumn(name = "laptop_id") 	private Laptop laptop; }                      
  • @ManyToOne annotation is used to add one to many relationships between two tables
  • @JoinColumn annotation is used to join a new column, this will be the foreign key column of the tbl_laptops table
  • @Data annotation which is a Lombok annotation, that will automatically create setters, getters, toString(), and equals() for us.
  • @Entity is a mandatory annotation that indicates that this class is a JPA entity and is mapped with a database table.
  • @Table annotation is an optional annotation that contains the table info like table name.
  • @Id annotation is a mandatory annotation that marks a field as the primary key

Create Laptop.java inside the in.bushansirgur.springboot.entity package and add the following content

            package in.bushansirgur.springboot.entity;  import java.math.BigDecimal; import java.util.List;  import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table;  import in.bushansirgur.springboot.request.LaptopRequest; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter;  @Entity @Table(name="tbl_laptops") @Getter @Setter @NoArgsConstructor public class Laptop { 	 	@Id 	@GeneratedValue(strategy = GenerationType.IDENTITY) 	private Long id; 	 	private String name; 	 	private String brand; 	 	private BigDecimal price; 	 	public Laptop(LaptopRequest request) { 		this.name = request.getName(); 		this.price = request.getPrice(); 		this.brand = request.getBrand(); 	} 	 }          

Create a Repository


Create an interface LaptopRepository.java inside the in.bushansirgur.springboot.repos package and add the following content

            package in.bushansirgur.springboot.repository;  import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;  import in.bushansirgur.springboot.entity.Laptop;  @Repository public interface LaptopRepository extends JpaRepository<Laptop, Long>{ 	 	 }                      

Create an interface ColorRepository.java inside the in.bushansirgur.springboot.repos package and add the following content

            package in.bushansirgur.springboot.repository;  import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;  import in.bushansirgur.springboot.entity.Color;  @Repository public interface ColorRepository extends JpaRepository<Color, Long> {  }                      

Create a Request class


Create a class LaptopRequest.java inside the in.bushansirgur.springboot.request package and add the following content

            package in.bushansirgur.springboot.request;  import java.math.BigDecimal; import java.util.List;  import lombok.Getter; import lombok.Setter;  @Setter @Getter public class LaptopRequest { 	 	private String name; 	 	private String brand; 	 	private BigDecimal price; 	 	private List<String> colors; 	 	 }                      

This is just a plain old java object (POJO), contains private fields, setters, and getters. This class is used to send the JSON payload from the client.

Create a Response class


Create a class LaptopResponse.java inside the in.bushansirgur.springboot.response package and add the following content

            package in.bushansirgur.springboot.response;  import java.math.BigDecimal; import java.util.List;  import lombok.Getter; import lombok.Setter;  @Getter @Setter public class LaptopResponse { 	 	private Long id; 	 	private String laptop; 	 	private BigDecimal price; 	 	private String brand; 	 	private List<String> colors; 	 }                      

Create a class ColorResponse.java inside the in.bushansirgur.springboot.response package and add the following content

            package in.bushansirgur.springboot.response;  import java.math.BigDecimal;  import lombok.Getter; import lombok.Setter;  @Setter @Getter public class ColorResponse { 	 	private Long id; 	 	private String laptop; 	 	private BigDecimal price; 	 	private String brand; 	 	private String color; }                      

These are just plain old java objects (POJOs) that contain private fields, setters, and getters. These response classes are used to send the final JSON to the client.

Create a Rest controller


Create LaptopController.java inside the in.bushansirgur.springboot.controller package and add the following content

            package in.bushansirgur.springboot.controller;  import java.util.ArrayList; import java.util.List;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController;  import in.bushansirgur.springboot.entity.Color; import in.bushansirgur.springboot.entity.Laptop; import in.bushansirgur.springboot.repository.ColorRepository; import in.bushansirgur.springboot.repository.LaptopRepository; import in.bushansirgur.springboot.request.LaptopRequest; import in.bushansirgur.springboot.response.LaptopResponse;  @RestController public class LaptopController { 	 	@Autowired 	private LaptopRepository lRepo; 	 	@Autowired 	private ColorRepository cRepo; 	 	@PostMapping("/laptops/save") 	public ResponseEntity<Laptop> saveData (@RequestBody LaptopRequest req) { 		 		Laptop laptop = new Laptop(req); 		laptop = lRepo.save(laptop); 		 		for (String s : req.getColors()) { 			Color c = new Color(); 			c.setColor(s); 			c.setLaptop(laptop); 			cRepo.save(c); 		} 		return new ResponseEntity<>(laptop, HttpStatus.CREATED); 		 	} }                      

Create ColorController.java inside the in.bushansirgur.springboot.controller package and add the following content

            package in.bushansirgur.springboot.controller;  import java.util.ArrayList; import java.util.List;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;  import in.bushansirgur.springboot.entity.Color; import in.bushansirgur.springboot.repository.ColorRepository; import in.bushansirgur.springboot.response.ColorResponse;  @RestController public class ColorController { 	 	@Autowired 	private ColorRepository cRepo; 	 	@GetMapping("/colors") 	public List<ColorResponse> getColors () { 		List<Color> list = cRepo.findAll(); 		List<ColorResponse> responseList = new ArrayList<>(); 		list.forEach(c -> { 			ColorResponse response = new ColorResponse(); 			response.setId(c.getId()); 			response.setLaptop(c.getLaptop().getName()); 			response.setBrand(c.getLaptop().getBrand()); 			response.setPrice(c.getLaptop().getPrice()); 			response.setColor(c.getColor()); 			responseList.add(response); 		}); 		return responseList; 	} }                      

Run the app


Run the application using the below maven command –

            mvn spring-boot:run          

Open the browser and enter the following URL –

  • localhost:8080/colors

Screenshot-2021-06-17-at-6-46-36-PM
That's it for this post, I hope you guys enjoyed this post. If you did, please share this post with your friends and colleagues. Also, share this post on your social media profile. Thanks, I will see you in the next post.


Post Views: 540

Spring Boot Crud Example Using One to Many Mapping

Source: https://bushansirgur.in/spring-data-jpa-one-to-many-uni-directional-example/

Related Posts

0 Response to "Spring Boot Crud Example Using One to Many Mapping"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel