How to create One-to-One Relationship Database and implementation in Spring boot and MySQL?
Hallo in this tutorial i want to create simple application for One-to-one Relationship Database implementation in spring boot and database mysql. One-to-One Relationship this is the common type of Relationship in a data model, where a line connection the two entities. this is example diagram like this :
Example Diagram one-to-one Relationship
The Next this is requirtment project for create aplication :
Requirtment Project :
- Java Version 17.0.2 : https://jdk.java.net/archive/
- Apache Maven 3.9.3 : https://maven.apache.org/download.cgi
- Mysql : https://www.mysql.com/downloads/
- Postman : https://www.postman.com/downloads/
- Intellij IDEA
: https://www.jetbrains.com/idea/download/?section=windows
Step first, Set up and Generate project Spring Boot with using Web
Spring Initializr, you can access Spring Initializr at
https://start.spring.io/ and than this is example project, you can follow the
set up this is example.
After Set Up Project Spring Boot next step click Generate for download the
application project and than extract the application and than open the
application using application Intellij IDEA
Before configutation application spring, you must create a Database in MySQL
with the name "db_spring_one_on_one". after create Database go to file
application.properties and configuration for connection this is project and
Database MySQL, you can open file application.properties at the path
src\main\resources\application.properties
this is example configuration for connection Database MySQL in application.properties:
spring.application.name=spring-boot-one-on-one
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/db_spring_one_on_one
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
Create Structure Folder and file such this is :
# controller (folder)
- CapitalController (class)
- CountryController (class)
# model (folder)
- Capital (class)
- Country (class)
# repository (folder)
- CapitalRepository (interface)
- CountryRepository (interface)
# Service (folder)
- CapitalImplService (interface)
- CapitalService (class)
- CountryImplService (interface)
- CountryService (class)
This is example structure folder and file :
- Model Country
This is a class file for Model Country (Country)
package com.blackcode.spring_boot_one_on_one.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
@JsonIgnoreProperties({"hibernateLazyInitializer"})
@Entity
@Table(name = "country")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long country_id;
private String country_name;
public Country() {
}
public Country(Long country_id, String country_name) {
this.country_id = country_id;
this.country_name = country_name;
}
public Long getCountry_id() {
return country_id;
}
public void setCountry_id(Long country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
- Model Capital
This is a class file for Model Capital (Capital)
package com.blackcode.spring_boot_one_on_one.model;
import jakarta.persistence.*;
@Entity
@Table(name = "capitals")
public class Capital {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long capital_id;
private String capital_name;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;
public Capital() {
}
public Capital(Long capital_id, String capital_name, Country country) {
this.capital_id = capital_id;
this.capital_name = capital_name;
this.country = country;
}
public Long getCapital_id() {
return capital_id;
}
public void setCapital_id(Long capital_id) {
this.capital_id = capital_id;
}
public String getCapital_name() {
return capital_name;
}
public void setCapital_name(String capital_name) {
this.capital_name = capital_name;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
- Repository Country
This is a interface for Repository Country (CountryRepository)
package com.blackcode.spring_boot_one_on_one.repository;
import com.blackcode.spring_boot_one_on_one.model.Country;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CountryRepository extends JpaRepository<Country, Long> {
}
- Repository Capital
This is a interface for Repository Capital (CapitalRepository)
package com.blackcode.spring_boot_one_on_one.repository;
import com.blackcode.spring_boot_one_on_one.model.Capital;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CapitalRepository extends JpaRepository<Capital, Long> {
}
- Service Country
This is a interface for Service Country (CountryService)
package com.blackcode.spring_boot_one_on_one.service;
import com.blackcode.spring_boot_one_on_one.model.Country;
import java.util.List;
public interface CountryService {
List<Country> getListAll();
Country getCountryById(Long id);
Country addCountry(Country country);
Country updateCountry(Long id, Country country);
boolean deleteCountry(Long id);
}
- Service Capital
This is a interface for Service Capital (CapitalService)
package com.blackcode.spring_boot_one_on_one.service;
import com.blackcode.spring_boot_one_on_one.model.Capital;
import java.util.List;
import java.util.Optional;
public interface CapitalService {
List<Capital> getListAll();
Optional<Capital> getCapitalById(Long id);
Capital addCapital(Capital capital);
Capital updateCapital(Long id, Capital capital);
boolean deleteCapital(Long id);
}
- Service Implementation Country
This is a class for Service Implementation Country (CountryImplService)
package com.blackcode.spring_boot_one_on_one.service;
import com.blackcode.spring_boot_one_on_one.model.Country;
import com.blackcode.spring_boot_one_on_one.repository.CapitalRepository;
import com.blackcode.spring_boot_one_on_one.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CountryImplService implements CountryService {
@Autowired
CountryRepository countryRepository;
@Autowired
CapitalRepository capitalRepository;
@Override
public List<Country> getListAll() {
return countryRepository.findAll();
}
@Override
public Country getCountryById(Long id) {
Optional<Country> countryTemp = countryRepository.findById(id);
return countryTemp.get();
}
@Override
public Country addCountry(Country country) {
Country countryData = new Country();
countryData.setCountry_name(country.getCountry_name());
return countryRepository.save(countryData);
}
@Override
public Country updateCountry(Long id, Country country) {
Optional<Country> countryData = countryRepository.findById(id);
Country countryTmp = countryData.get();
countryTmp.setCountry_name(country.getCountry_name());
return countryRepository.save(countryTmp);
}
@Override
public boolean deleteCountry(Long id) {
Optional<Country> countryData = countryRepository.findById(id);
if(countryData.isPresent()){
capitalRepository.deleteById(countryData.get().getCountry_id());
countryRepository.deleteById(id);
return true;
}else{
return false;
}
}
}
- Service Implementation Capital
This is a class for Service Implementation Capital (CapitalImplService)
package com.blackcode.spring_boot_one_on_one.service;
import com.blackcode.spring_boot_one_on_one.model.Capital;
import com.blackcode.spring_boot_one_on_one.model.Country;
import com.blackcode.spring_boot_one_on_one.repository.CapitalRepository;
import com.blackcode.spring_boot_one_on_one.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class CapitalImplService implements CapitalService {
@Autowired
private CountryRepository countryRepository;
@Autowired
private CapitalRepository capitalRepository;
@Override
public List<Capital> getListAll() {
return capitalRepository.findAll();
}
@Override
public Optional<Capital> getCapitalById(Long id) {
return capitalRepository.findById(id);
}
@Override
public Capital addCapital(Capital capital) {
Capital capitalData = new Capital();
capitalData.setCapital_name(capital.getCapital_name());
Optional<Country> country = countryRepository.findById(capital.getCountry().getCountry_id());
capitalData.setCountry(country.get());
return capitalRepository.save(capitalData);
}
@Override
public Capital updateCapital(Long id, Capital capital) {
Optional<Capital> capital1 = capitalRepository.findById(id);
Capital capitalTemp = capital1.get();
capitalTemp.setCapital_name(capital.getCapital_name());
return capitalRepository.save(capitalTemp);
}
@Override
public boolean deleteCapital(Long id) {
Optional<Capital> capitalData = capitalRepository.findById(id);
if(capitalData.isPresent()){
capitalRepository.deleteById(id);
return true;
}else{
return false;
}
}
}
- Controller Country
This is a class for Controller Country (CountryController)
package com.blackcode.spring_boot_one_on_one.controller;
import com.blackcode.spring_boot_one_on_one.model.Country;
import com.blackcode.spring_boot_one_on_one.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/country")
public class CountryController {
@Autowired
private CountryService countryService;
@GetMapping
public ResponseEntity<List<Country>> getAll(){
return ResponseEntity.ok(countryService.getListAll());
}
@GetMapping("/{id}")
public ResponseEntity<Country> getById(@PathVariable Long id){
Country country = countryService.getCountryById(id);
return new ResponseEntity<>(country, HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Country> addCountry(@RequestBody Country country){
Country countryData = countryService.addCountry(country);
return new ResponseEntity<>(countryData, HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Country> updateCountry(@PathVariable Long id, @RequestBody Country country){
Country countryData = countryService.updateCountry(id, country);
return new ResponseEntity<>(countryData, HttpStatus.CREATED);
}
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteCountry(@PathVariable Long id){
boolean country = countryService.deleteCountry(id);
if(country){
return new ResponseEntity<>("Data "+id+" Successfully Delete", HttpStatus.OK);
}
return new ResponseEntity<>("Data "+id+" Not Found", HttpStatus.NOT_FOUND);
}
}
- Controller Capital
This is a class for Controller Capital (CapitalController)
package com.blackcode.spring_boot_one_on_one.controller;
import com.blackcode.spring_boot_one_on_one.model.Capital;
import com.blackcode.spring_boot_one_on_one.service.CapitalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping("/api/capital")
public class CapitalController {
@Autowired
private CapitalService capitalService;
@GetMapping
public ResponseEntity<List<Capital>> getListAll(){
return ResponseEntity.ok(capitalService.getListAll());
}
@GetMapping("/{id}")
public ResponseEntity<Capital> getById(@PathVariable Long id){
Optional<Capital> capital = capitalService.getCapitalById(id);
return new ResponseEntity<>(capital.get(), HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Capital> addCapital(@RequestBody Capital capital){
Capital capital1 = capitalService.addCapital(capital);
return new ResponseEntity<>(capital1, HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<Capital> updateCapital(@PathVariable Long id, @RequestBody Capital capital){
Capital capital1 = capitalService.updateCapital(id, capital);
return new ResponseEntity<>(capital1, HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteCapital(@PathVariable Long id){
boolean capital = capitalService.deleteCapital(id);
if(capital){
return new ResponseEntity<>("Data "+id+" Successfully Delete", HttpStatus.OK);
}
return new ResponseEntity<>("Data not Found", HttpStatus.NOT_FOUND);
}
}
And than running project using command in terminal intelij IDEA
mvn spring-boot:run
Testing Application using Postman
- Create Country
- Get List All Data Country
- Get Data Country By id
- Update Data Country
- Delete Data Country
- Create Capital Data
- Get List All Data Capital
- Get Data Capital By id
- Update Data Capital
- Delete Data Capital
Project Source Code : https://github.com/rardan97/spring-boot-one-on-one

.png)















Komentar
Posting Komentar