개발자의 서재

Chaptor.06 - 상품,주문 entity, repository, dto, servcie, controller (API) 추가 본문

SpringBootProject/SringBoot_JWT_RestApi

Chaptor.06 - 상품,주문 entity, repository, dto, servcie, controller (API) 추가

ironmask431 2022. 4. 3. 23:38

 

<진행할 것>

- 상품,주문 entity, dto, servcie, controller 추가

 

Entity 관계도(ERD)

 

1. entity 생성 

Product.java

package com.leesh.springbootjwttutorial.entity;

import lombok.*;

import javax.persistence.*;

/**
 * 상품 entity
 */
@Entity
@Table(name="product")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Product {

    @Id
    @Column(name="prd_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY) // auto increment
    private Long prdId;

    @Column(name="prd_nm", length = 100)
    private String prdNm;

    @Column(name="price")
    private int price;
}

Order.java

package com.leesh.springbootjwttutorial.entity;

import lombok.*;

import javax.persistence.*;

/**
 * 주문 entity
 */
@Entity
@Table(name="order_table")
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Order {

    @Id
    @Column(name="ord_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY) // auto increment
    private Long ordId;

    @Column(name="user_id")
    private Long userId;

    @Column(name="prd_id")
    private Long prdId;

}

 

2.repository 생성

ProductRepository.java 

package com.leesh.springbootjwttutorial.repository;

import com.leesh.springbootjwttutorial.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product,Long> {
}

OrderRepository.java

package com.leesh.springbootjwttutorial.repository;

import com.leesh.springbootjwttutorial.entity.Order;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface OrderRepository extends JpaRepository<Order, Long> {
    List<Order> findByUserId(Long userId);
}

3. dto 생성 

ProductDto.java

package com.leesh.springbootjwttutorial.dto;


import com.leesh.springbootjwttutorial.entity.Product;
import lombok.*;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ProductDto {

    private Long prdId;

    @NotNull
    @Size(max=100)
    private String prdNm;

    @NotNull
    private int price;

    public ProductDto(Product entity){
        this.prdId = entity.getPrdId();
        this.prdNm = entity.getPrdNm();
        this.price = entity.getPrice();
    }
}

OrderDto.java

package com.leesh.springbootjwttutorial.dto;

import com.leesh.springbootjwttutorial.entity.Order;
import lombok.*;

import javax.validation.constraints.NotNull;

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class OrderDto {

    private Long ordId;

    private Long userId;

    @NotNull
    private Long prdId;

    private ProductDto productDto;

    public OrderDto(Order entity){
        this.ordId = entity.getOrdId();
        this.userId = entity.getUserId();
        this.prdId = entity.getPrdId();
    }
}

 

4. service 생성 

ProductService.java 

package com.leesh.springbootjwttutorial.service;

import com.leesh.springbootjwttutorial.dto.ProductDto;
import com.leesh.springbootjwttutorial.entity.Product;
import com.leesh.springbootjwttutorial.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class ProductService {
    private final ProductRepository productRepository;

    //상품목록 전제 조회
    @Transactional(readOnly = true)
    public List<ProductDto> findAll(){
        return productRepository.findAll().stream()
                .map(product-> {return new ProductDto(product);}).collect(Collectors.toList());
    }

    //상품번호로 상품 조회
    @Transactional(readOnly = true)
    public ProductDto findById(Long prdId){
        Product product = productRepository.findById(prdId)
                .orElseThrow(()-> new IllegalArgumentException("해당 상품번호가 없습니다. prdId="+prdId));
        ProductDto productDto = new ProductDto(product);
        return productDto;
    }
}

OrderService.java

package com.leesh.springbootjwttutorial.service;

import com.leesh.springbootjwttutorial.dto.OrderDto;
import com.leesh.springbootjwttutorial.dto.UserDto;
import com.leesh.springbootjwttutorial.entity.Order;
import com.leesh.springbootjwttutorial.repository.OrderRepository;
import com.leesh.springbootjwttutorial.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class OrderService {
    private final OrderRepository orderRepository;
    private final UserService userService;
    private final ProductService productService;

    //주문목록 전제 조회
    @Transactional(readOnly = true)
    public List<OrderDto> findAll(){
        List<OrderDto> orderDtoList = orderRepository.findAll().stream()
                .map(order -> {return new OrderDto(order);}).collect(Collectors.toList());

        for(OrderDto orderDto : orderDtoList){
            settingProductDto(orderDto);
        }

        return orderDtoList;
    }

    //주문번호로 주문 조회
    @Transactional(readOnly = true)
    public OrderDto findById(Long ord_id){
        //ord_id로 주문정보 조회
        Order order = orderRepository.findById(ord_id)
                .orElseThrow(()-> new IllegalArgumentException("해당 주문번호가 없습니다. ord_id="+ord_id));

        //orderDto 생성
        OrderDto orderDto = new OrderDto(order);

        settingProductDto(orderDto);

        return orderDto;
    }

    //userId 로 주문목록 조회
    @Transactional(readOnly = true)
    public List<OrderDto> findByUserId(Long userId){

        List<OrderDto> orderDtoList = orderRepository.findByUserId(userId).stream()
                .map(order -> {return new OrderDto(order);}).collect(Collectors.toList());

        for(OrderDto orderDto : orderDtoList){
            settingProductDto(orderDto);
        }
        return orderDtoList;
    }

    //현재 인증된 사용자의 주문목록 조회
    @Transactional(readOnly = true)
    public List<OrderDto> findByMyUserId(){
        //현재 인증된 사용자의 userId 조회
        UserDto userDto = new UserDto(userService.getMyUserWithAuthorities().get());
        Long userId = userDto.getUserId();
        log.info("findByMyUserId - userId="+userId);

        List<OrderDto> orderDtoList = orderRepository.findByUserId(userId).stream()
                .map(order -> {return new OrderDto(order);}).collect(Collectors.toList());

        for(OrderDto orderDto : orderDtoList){
            settingProductDto(orderDto);
        }
        return orderDtoList;
    }

    //주문 입력
    public OrderDto save(OrderDto orderDto){
        //주문 받은 prdId 검증
        productService.findById(orderDto.getPrdId());

        //현재 인증된 사용자의 userId 조회
        UserDto userDto = new UserDto(userService.getMyUserWithAuthorities().get());
        Long userId = userDto.getUserId();
        log.info("save - userId="+userId);

        //Order Entity 생성
        Order order = Order.builder()
                .userId(userId)
                .prdId(orderDto.getPrdId())
                .build();

        order = orderRepository.save(order);

        orderDto = new OrderDto(order);
        settingProductDto(orderDto);

        return orderDto;
    }

    //orderDto의 prdId로 상품정보 조회하여 orderDto 의 productDto 필드에 입력
    public void settingProductDto(OrderDto orderDto){
        orderDto.setProductDto(productService.findById(orderDto.getPrdId()));
    }
}

5. controller 생성

ProductController.java 

package com.leesh.springbootjwttutorial.controller;

import com.leesh.springbootjwttutorial.dto.ProductDto;
import com.leesh.springbootjwttutorial.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 상품API 컨트롤러
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/product")
public class ProductController {
    private final ProductService productService;

    //전체 상품 조회
    @GetMapping("/all")
    public List<ProductDto> findAll(){
        return productService.findAll();
    }

    //상품번호로 주문 조회
    @GetMapping("/prdId/{prdId}")
    public ProductDto findById(@PathVariable Long prdId){
        return productService.findById(prdId);
    }
}

OrderController.java

package com.leesh.springbootjwttutorial.controller;

import com.leesh.springbootjwttutorial.dto.OrderDto;
import com.leesh.springbootjwttutorial.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 주문 API 컨트롤러
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/order")
public class OrderController {
    private final OrderService orderService;

    //전체 주문 조회
    @GetMapping("/all")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public List<OrderDto> findAll(){
        return orderService.findAll();
    }

    //주문번호로 주문 조회
    @GetMapping("/ordId/{ordId}")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public OrderDto findById(@PathVariable Long ordId){
        return orderService.findById(ordId);
    }

    //userId 로 주문 조회
    @GetMapping("/userId/{userId}")
    @PreAuthorize("hasAnyRole('ADMIN')")
    public List<OrderDto> findByUserId(@PathVariable Long userId){
        return orderService.findByUserId(userId);
    }

    //현재 인증된 사용자의 주문 조회 (나의 주문조회)
    @GetMapping("/myOrder")
    public List<OrderDto> findByMyUserId(){
        return orderService.findByMyUserId();
    }

    //주문입력
    @PostMapping("/save")
    public OrderDto save(@Valid @RequestBody OrderDto orderDto){
        return orderService.save(orderDto);
    }
}

 

6. data.sql에 insert문 추가

INSERT INTO PRODUCT (PRD_ID, PRD_NM, PRICE) VALUES (1,'사과',5000);
INSERT INTO PRODUCT (PRD_ID, PRD_NM, PRICE) VALUES (2,'바나나',3000);
INSERT INTO PRODUCT (PRD_ID, PRD_NM, PRICE) VALUES (3,'딸기',7000);
INSERT INTO PRODUCT (PRD_ID, PRD_NM, PRICE) VALUES (4,'토마토',4000);
INSERT INTO PRODUCT (PRD_ID, PRD_NM, PRICE) VALUES (5,'수박',10000);

INSERT INTO ORDER_TABLE (ORD_ID, USER_ID, PRD_ID) VALUES (1,1,1);
INSERT INTO ORDER_TABLE (ORD_ID, USER_ID, PRD_ID) VALUES (2,1,2);

 

7. postman api 테스트

 

 

Comments