Skip to content

[4기 황창현, 이현호] JPA Mission 3 - 도메인 연관관계 매핑 실습 #302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: 창현,현호-mission2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e9efc1d
feat: Order 도메인 추가
Hchanghyeon Jul 29, 2023
25fd6b6
refactor: orders 도메인 수정
Hchanghyeon Jul 29, 2023
d9b65f4
refactor: Customer 도메인 컬럼 속성 수정
Hchanghyeon Jul 29, 2023
710b5e5
feat: Item 도메인 구현
Hchanghyeon Jul 29, 2023
bf23613
feat: OrderItem 도메인 구현
Hchanghyeon Jul 29, 2023
ae6d950
feat: Customer와 Order 양방향 연관관계 설정
Hchanghyeon Jul 29, 2023
5af566a
feat: Order와 OrderItem, OrderItem과 Item연관관계 매핑 설정
Hchanghyeon Jul 29, 2023
9f20261
refactor: 폴더 구성 변경
Hchanghyeon Jul 29, 2023
07a953e
feat: Item, OrderItem, Order Repository구현
Hchanghyeon Jul 29, 2023
4b0946b
feat: 도메인 연관관계 테스트
Hchanghyeon Jul 29, 2023
79abaee
refactor: AssociationTest 디렉터리 위치 변경
Hchanghyeon Jul 29, 2023
358544f
refactor: controller에서 ResponseStatus를 활용하여 처리
Hchanghyeon Aug 4, 2023
a34dee8
refactor: 메서드 명 변경
Hchanghyeon Aug 4, 2023
737fa92
refactor: update에 대한 rest api 로직 변경
Hchanghyeon Aug 4, 2023
f5c3dc7
refactor: 어노테이션이붙은 필드명과 필드명사이 개행 처리
Hchanghyeon Aug 4, 2023
39c94fe
refactor: message 오타 수정
Hchanghyeon Aug 4, 2023
a1af086
refactor: service 메소드 네이밍 수정
Hchanghyeon Aug 4, 2023
c64bb48
refactor: customer를 메소드 네이밍에서 삭제
Hchanghyeon Aug 4, 2023
e3a73f6
refactor: 연관관계 메소드 수정
Hchanghyeon Aug 4, 2023
c6668a7
refactor: 필드 사이에 한칸씩 개행
Hchanghyeon Aug 4, 2023
e136bc8
test: beforeEach로 테스트코드 간결화
Hchanghyeon Aug 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;


Expand All @@ -27,37 +27,32 @@ public class CustomerController {
private final CustomerService customerService;

@PostMapping
public ResponseEntity<Void> createCustomer(@Valid @RequestBody CustomerCreateRequest customerCreateRequest) {
customerService.createCustomer(customerCreateRequest);

return ResponseEntity.status(HttpStatus.CREATED).body(null);
@ResponseStatus(HttpStatus.CREATED)
public void create(@Valid @RequestBody CustomerCreateRequest customerCreateRequest) {
customerService.create(customerCreateRequest);
}

@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> readCustomer(@PathVariable Long id) {
CustomerResponse customerResponse = customerService.readCustomer(id);

return ResponseEntity.ok(customerResponse);
@ResponseStatus(HttpStatus.OK)
public CustomerResponse readById(@PathVariable Long id) {
return customerService.readById(id);
}

@GetMapping
public ResponseEntity<List<CustomerResponse>> readAllCustomer() {
List<CustomerResponse> customerResponses = customerService.readAllCustomer();

return ResponseEntity.ok(customerResponses);
@ResponseStatus(HttpStatus.OK)
public List<CustomerResponse> readAll() {
return customerService.readAll();
}

@PatchMapping
public ResponseEntity<Void> updateCustomer(@Valid @RequestBody CustomerUpdateRequest customerUpdateRequest) {
customerService.updateCustomer(customerUpdateRequest);

return ResponseEntity.ok(null);
@PatchMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
public void updateById(@PathVariable Long id, @Valid @RequestBody CustomerUpdateRequest customerUpdateRequest) {
customerService.updateById(id, customerUpdateRequest);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteCustomer(@PathVariable Long id) {
customerService.deleteCustomer(id);

return ResponseEntity.noContent().build();
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteById(@PathVariable Long id) {
customerService.deleteById(id);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.programmers.springbootjpa.domain;
package com.programmers.springbootjpa.domain.customer;

import jakarta.persistence.Column;
import jakarta.persistence.Embeddable;
Expand All @@ -13,8 +13,10 @@ public class Address {

@Column(name = "street_address", nullable = false)
private String streetAddress;

@Column(name = "detailed_address", nullable = false)
private String detailedAddress;

@Column(name = "zip_code", nullable = false)
private Integer zipCode;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package com.programmers.springbootjpa.domain;
package com.programmers.springbootjpa.domain.customer;

import com.programmers.springbootjpa.domain.order.Order;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -26,12 +31,15 @@ public class Customer {
@Column(name = "age", nullable = false)
private Integer age;

@Column(name = "nick_name", nullable = false)
@Column(name = "nick_name", nullable = false, unique = true, length = 20)
private String nickName;

@Embedded
private Address address;

@OneToMany(mappedBy = "customer")
private List<Order> orders = new ArrayList<>();

@Builder
public Customer(String name, Integer age, String nickName, Address address) {
this.name = name;
Expand All @@ -40,6 +48,18 @@ public Customer(String name, Integer age, String nickName, Address address) {
this.address = address;
}

public List<Order> getOrders() {
return Collections.unmodifiableList(orders);
}

public void add(Order order) {
this.orders.add(order);
}

public void remove(Order order) {
this.orders.remove(order);
}

public void changeNickName(String nickName) {
this.nickName = nickName;
}
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/com/programmers/springbootjpa/domain/item/Item.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.programmers.springbootjpa.domain.item;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "item")
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Item {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
private Integer price;
private Integer stockQuantity;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Order 클래스의 리뷰를 참고하여 연관관계 편의 메소드에서 사용할 add,remove 메소드를 만들수 있을 것 같아요!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Item의 경우 단방향 연관관계로 매핑되어 있어서 편의 메서드를 쓸 수 없다고 생각했습니다!

@Builder
public Item(String name, Integer price, Integer stockQuantity) {
this.name = name;
this.price = price;
this.stockQuantity = stockQuantity;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.programmers.springbootjpa.domain.order;

import com.programmers.springbootjpa.domain.customer.Customer;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.LocalDateTime;
import java.util.Objects;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Table(name = "orders")
@Getter
public class Order {

@Id
@Column(name = "id", nullable = false)
private String uuid;

@Column(name = "order_datetime", columnDefinition = "TIMESTAMP", nullable = false)
private LocalDateTime orderDatetime;

@Enumerated(EnumType.STRING)
@Column(name = "order_status", nullable = false)
private OrderStatus orderStatus;

@Column(name = "memo", columnDefinition = "TEXT")
private String memo;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customer_id", referencedColumnName = "id")
private Customer customer;

@Builder
public Order(String uuid, LocalDateTime orderDatetime, OrderStatus orderStatus, String memo) {
this.uuid = uuid;
this.orderDatetime = orderDatetime;
this.orderStatus = orderStatus;
this.memo = memo;
}

public void setCustomer(Customer customer) {
if (Objects.nonNull(this.customer)) {
this.customer.remove(this);
}

this.customer = customer;
customer.add(this);
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이쪽 부분에도 OrderItem연관관계 편의 메소드에서 사용할 add,remove 메소드를 만들 수 있을 것 같아요!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Order역시 OrderItem과의 연관 관계는 단방향이라서 편의 메서드를 만들지 않았습니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.programmers.springbootjpa.domain.order;

import com.programmers.springbootjpa.domain.item.Item;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Getter
@Table(name = "order_item")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class OrderItem {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;

private Integer price;

private Integer quantity;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", referencedColumnName = "id")
private Order order;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "item_id", referencedColumnName = "id")
private Item item;

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Order, Item 클래스의 연관관계 편의 메소드를 만들어주세요!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

단방향이라서 편의 메서드는 만들 수 없었습니다.

@Builder
public OrderItem(Integer price, Integer quantity, Order order, Item item) {
this.price = price;
this.quantity = quantity;
this.order = order;
this.item = item;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.programmers.springbootjpa.domain.order;

public enum OrderStatus {
OPENED,
CANCELLED
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.programmers.springbootjpa.dto.request;

import com.programmers.springbootjpa.domain.Address;
import com.programmers.springbootjpa.domain.Customer;
import com.programmers.springbootjpa.domain.customer.Address;
import com.programmers.springbootjpa.domain.customer.Customer;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
Expand All @@ -16,12 +16,15 @@ public class CustomerCreateRequest {

@NotBlank(message = "이름은 공백이거나 값이 없으면 안됩니다.")
private String name;

@Min(value = 1, message = "나이는 한살보다 많아야합니다.")
@Max(value = 100, message = "나이는 백살보다 적여야합니다.")
@Max(value = 100, message = "나이는 백살보다 적어야합니다.")
@NotNull(message = "나이는 값이 없으면 안됩니다.")
private Integer age;

@NotBlank(message = "닉네임은 공백이거나 값이 없으면 안됩니다.")
private String nickName;

@NotNull(message = "주소값은 없을 수 없습니다.")
private Address address;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package com.programmers.springbootjpa.dto.request;

import com.programmers.springbootjpa.domain.Address;
import com.programmers.springbootjpa.domain.customer.Address;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -12,10 +11,9 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CustomerUpdateRequest {

@PositiveOrZero(message = "id값은 0이상 이어야합니다.")
private Long id;
@NotBlank(message = "닉네임은 공백이거나 값이 없으면 안됩니다.")
private String nickName;

@NotNull(message = "주소값은 없을 수 없습니다.")
private Address address;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.programmers.springbootjpa.dto.response;

import com.programmers.springbootjpa.domain.Address;
import com.programmers.springbootjpa.domain.Customer;
import com.programmers.springbootjpa.domain.customer.Address;
import com.programmers.springbootjpa.domain.customer.Customer;
import lombok.Getter;

@Getter
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.programmers.springbootjpa.repository;

import com.programmers.springbootjpa.domain.Customer;
import com.programmers.springbootjpa.domain.customer.Customer;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository<Customer, Long> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.programmers.springbootjpa.repository;

import com.programmers.springbootjpa.domain.item.Item;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemRepository extends JpaRepository<Item, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.programmers.springbootjpa.repository;

import com.programmers.springbootjpa.domain.order.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.programmers.springbootjpa.repository;

import com.programmers.springbootjpa.domain.order.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, String> {

}
Loading