Spring Boot 일대일 매핑 예 - 일대일 매핑을 사용하는 Spring Crud 예
20941 단어 springboot
자습서: "Spring Boot 일대일 매핑 예 - 일대일 매핑을 사용한 Spring Crud 예제"
이 강좌에서는 SpringBoot과 PostgreSQL 데이터베이스를 사용하여 Hibernate Spring JPA와 일대일 관계 모델을 상호작용할 수 있도록 Crud Rest APIs
Post/Get/Put/Delete
을 공개하는 방법을 보여 드리겠습니다.개요 - 스프링 부트 일대일 매핑 예
Student
모델 2개와 Contact
one-to-one
관계: 다음과 같이 SpringBoot 프로젝트를 만들었습니다.
[caption id= "attachment 4772"align="alignnone"width="701"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql 아키텍처 [/caption]
[caption id= "attachment 4773"align="alignnone"width="346"] SpringBoot 프로젝트 구조 [/caption]
Hibernate JPA 구성은
Student
및 Contact
두 가지 모델로 제공됩니다.Student
모델 ->
@Entity
@Table(name = "students")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private int age;
@OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "student")
private Contact contact;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// Getters & Setters methods
// ...
- Contact
모델:
@Entity
@Table(name = "contacts")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Contact implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "city")
private String city;
@Column(name = "phone")
private String phone;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "student_id", nullable = false)
private Student student;
public Contact() {
}
public Contact(String city, String phone) {
this.city = city;
this.phone = phone;
}
// Getters & Setters methods
// ...
Post/Get/Put/Delete
명의 학생 및 담당자에게 RestAPIs를 소개합니다.- 학생 ->
@GetMapping("/api/students")
: 모든 학생에게 @GetMapping("/api/students/{id}")
: ID가 @PostMapping("/api/students")
: 학생 1명 발표 @PutMapping("/api/students/{id}")
: 업데이트 학생 @DeleteMapping("/api/students/{id}")
: 학생 삭제 @GetMapping("/contacts")
: 모든 연락처 찾기 @GetMapping("/students/{studentId}/contacts")
: 학생 ID @PostMapping("/students/{studentId}/contacts")
: 연락처 추가 @PutMapping("/contacts/{contactId}")
: 연락처 업데이트 @DeleteMapping("/contacts/{contactId}")
: ID가 이제 우리는 처음부터 프로젝트를 만들 것이다.가자!
SpringBoot 프로젝트 만들기 - SpringBoot 일대일 매핑 예
SpringToolSuite를 사용하여 다음과 같은 종속 항목이 있는
Java 8
SpringBoot 프로젝트를 만들었습니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
SpringBoot OneToOne 모델 - 스프링 부트 일대일 매핑 예
-
Student
모델 ->code class="language-java"> package com.ozenero.springrestapi.onetoone.model; import java.io.Serializable; 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.OneToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "students") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Student implements Serializable { private static final long serialVersionUID = 1L; @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private int age; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "student") private Contact contact; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public void setId(Long id) { this.id = id; } public Long getId() { return this.id; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setAge(int age) { this.age =age; } public int getAge() { return this.age; } }-
Contact
model :
package com.ozenero.springrestapi.onetoone.model;
import java.io.Serializable;
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.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "contacts")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Contact implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "city")
private String city;
@Column(name = "phone")
private String phone;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "student_id", nullable = false)
private Student student;
public Contact() {
}
public Contact(String city, String phone) {
this.city = city;
this.phone = phone;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return this.city;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return this.phone;
}
public void setStudent(Student student) {
this.student = student;
}
public Student getStudent() {
return this.student;
}
}
SpringBoot JPA 저장소 - 스프링 부트 일대일 매핑 예
-
StudentRepository
:
package com.ozenero.springrestapi.onetoone.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ozenero.springrestapi.onetoone.model.Student;
public interface StudentRepository extends JpaRepository {
}
- ContactRepository
모델:
package com.ozenero.springrestapi.onetoone.jpa;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ozenero.springrestapi.onetoone.model.Contact;
public interface ContactRepository extends JpaRepository {
List findByStudentId(Long studentId);
}
application.properties
파일에 데이터 소스 구성을 추가하려면:
spring.datasource.url=jdbc:postgresql://localhost/testdb
spring.datasource.username=postgres
spring.datasource.password=123
spring.jpa.generate-ddl=true
#spring.jackson.serialization.fail-on-empty-beans=false
SpringBoot Rest API-spring Boot 일대일 매핑 예 공개
-
StudentController
:
package com.ozenero.springrestapi.onetoone.rest;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ozenero.springrestapi.onetoone.exception.NotFoundException;
import com.ozenero.springrestapi.onetoone.jpa.StudentRepository;
import com.ozenero.springrestapi.onetoone.model.Student;
@RestController
@RequestMapping("/api")
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@GetMapping("/students")
public List getAllStudents() {
return studentRepository.findAll();
}
@GetMapping("/students/{id}")
public Student getStudentByID(@PathVariable Long id) {
Optional optStudent = studentRepository.findById(id);
if(optStudent.isPresent()) {
return optStudent.get();
}else {
throw new NotFoundException("Student not found with id " + id);
}
}
@PostMapping("/students")
public Student createStudent(@Valid @RequestBody Student student) {
return studentRepository.save(student);
}
@PutMapping("/students/{id}")
public Student updateStudent(@PathVariable Long id,
@Valid @RequestBody Student studentUpdated) {
return studentRepository.findById(id)
.map(student -> {
student.setName(studentUpdated.getName());
student.setAge(studentUpdated.getAge());
return studentRepository.save(student);
}).orElseThrow(() -> new NotFoundException("Student not found with id " + id));
}
@DeleteMapping("/students/{id}")
public String deleteStudent(@PathVariable Long id) {
return studentRepository.findById(id)
.map(student -> {
studentRepository.delete(student);
return "Delete Successfully!";
}).orElseThrow(() -> new NotFoundException("Student not found with id " + id));
}
}
- ContactController
:
package com.ozenero.springrestapi.onetoone.rest;
import java.util.List;
import javax.validation.Valid;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ozenero.springrestapi.onetoone.exception.NotFoundException;
import com.ozenero.springrestapi.onetoone.jpa.ContactRepository;
import com.ozenero.springrestapi.onetoone.jpa.StudentRepository;
import com.ozenero.springrestapi.onetoone.model.Contact;
@RestController
@RequestMapping("/api")
public class ContactController {
@Autowired
private ContactRepository contactRepository;
@Autowired
private StudentRepository studentRepository;
@GetMapping("/contacts")
public List getAllContacts(){
return contactRepository.findAll();
}
@GetMapping("/students/{studentId}/contacts")
public Contact getContactByStudentId(@PathVariable Long studentId) {
if(!studentRepository.existsById(studentId)) {
throw new NotFoundException("Student not found!");
}
List contacts = contactRepository.findByStudentId(studentId);
if(contacts.size() > 0) {
return contacts.get(0);
}else {
throw new NotFoundException("Contact not found!");
}
}
@PostMapping("/students/{studentId}/contacts")
public Contact addContact(@PathVariable Long studentId,
@Valid @RequestBody Contact contact) {
return studentRepository.findById(studentId)
.map(student -> {
contact.setStudent(student);
return contactRepository.save(contact);
}).orElseThrow(() -> new NotFoundException("Student not found!"));
}
@PutMapping("/contacts/{contactId}")
public Contact updateContact(@PathVariable Long contactId,
@Valid @RequestBody Contact contactUpdated) {
return contactRepository.findById(contactId)
.map(contact -> {
contact.setCity(contactUpdated.getCity());
contact.setPhone(contactUpdated.getPhone());
return contactRepository.save(contact);
}).orElseThrow(() -> new NotFoundException("Contact not found!"));
}
@DeleteMapping("/contacts/{contactId}")
public String deleteContact(@PathVariable Long contactId) {
return contactRepository.findById(contactId)
.map(contact -> {
contactRepository.delete(contact);
return "Deleted Successfully!";
}).orElseThrow(() -> new NotFoundException("Contact not found!"));
}
}
실행 및 결과 확인
- 명령줄
mvn spring-boot:run
을 사용하여 SpringBoot 프로젝트를 실행합니다.PostgreSQL에는
[caption id= "attachment 4774"align="alignnone"width="358"] Spring Boot Rest API 휴면 Spring Jpa Jpa가 만든 일대일 Postgresql 표 [/caption]
- 학생 추가:
[caption id= "attachment 4775"align="alignnone"width="572"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql 표 - 학생 데이터 [/caption] 발표
- 연락처 추가:
[caption id= "attachment 4776"align="alignnone"width="566"] Spring Boot Rest API Hibernate Spring Jpa 일대일 Postgresql 연락처 [/caption]
- 연락처 업데이트:
[caption id= "attachment 4777"align="alignnone"width="569"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql Put 연락처 [/caption]
- 학생 업데이트:
[caption id = "attachment 4778"align="alignnone"width="588"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql 학생 [caption]
- 모든 학생에게
[caption id= "attachment 4779"align="alignnone"width="332"] Spring Boot Rest API Hibernate Spring Jpa 일대일 Postgresql Get All Student[/caption]
- 모든 연락처 검색:
[caption id = "attachment 4780"align="alignnone"width="330"] Spring Boot Rest API Hibernate Spring Jpa 일대일 Postgresql 모든 연락처 얻기 [/caption]
- 학생 삭제:
[caption id = "attachment 4781"align="alignnone"width="426"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql 표 삭제 학생 [/caption]
- 연락처 삭제:
[caption id= "attachment 4782"align="alignnone"width="392"] Spring Boot Rest API Hibernate Spring JPA 일대일 Postgresql 테이블에서 연락처 삭제 [/caption]
참고: PostgreSQL 명령줄:
PostgreSQL\9.6\bin>psql.exe --username="postgres" -W
: PostgreSQL에 연결->
C:\Program Files\PostgreSQL\9.6\bin>psql.exe --username="postgres" -W
Password for user postgres:
psql (9.6.9)
WARNING: Console code page (437) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
- \l
: 데이터베이스 목록-
\c testdb
: "testdb"에 연결-
\d
: 관계 목록 ->testdb=#\d
관계 목록
모드 | 이름 | 유형 | 소유자
--------+-----------------+----------+----------
공용 | 연락처 | 표 | 박사후
일반 | 연락처 | id | 순서 | 박사후
공공 | 학생 | 책상 | 박사후
공용|학생|신분|순서|대학원생
(4열)
testdb=# \q
: 출구자세히 보기
관련 직위:
소스 코드
SpringBoot-RestAPIs-OneToOne
Reference
이 문제에 관하여(Spring Boot 일대일 매핑 예 - 일대일 매핑을 사용하는 Spring Crud 예), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/loizenai/spring-boot-one-to-one-mapping-example-spring-crud-example-using-one-to-one-mapping-1i2g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)