Spring(기초)-4주차-2

Jonguk Kim·2021년 11월 18일
0

Spring

목록 보기
9/16

1. 프로젝트 설계하기

필요한 기능 확인하기

  1. 키워드로 상품 검색하고 그 결과를 목록으로 보여주기
  2. 관심 상품 등록하기
  3. 관심 상품 조회하기
  4. 관심 상품에 원하는 가격 등록하고, 그 가격보다 낮은 경우 표시하기

API 설계하기

3계층 설계하기

  1. Controller
    • ProductRestController: 관심 상품 관련 컨트롤러
    • SearchRequestController: 검색 관련 컨트롤러
  2. Service
    • ProductService: 관심 상품 가격 변경
  3. Repository
    • Product: 관심 상품 테이블
    • ProductRepository: 관심 상품 조회, 저장
    • ProductRequestDto: 관심 상품 등록하기
    • ProductMypriceRequestDto: 관심 가격 변경하기
    • ItemDto: 검색 결과 주고받기

2. 관심 상품 조회하기

  • models 패키지 생성 (src > main > java > com.sparta.week04 > models)

Timestamped 클래스 생성하기

  1. 멤버 변수 선언 (생성일자, 수정일자)
public class Timestamped {
    private LocalDateTime createdAt;
    private LocalDateTime modifiedAt;
}
  1. 최초 생성 / 마지막 변경 시점 선언
  2. 변경 시 자동 기록
@EntityListeners(AuditingEntityListener.class) // 3. 변경되었을 때 자동으로 기록합니다.
public class Timestamped {
    @CreatedDate // 2. 최초 생성 시점
    private LocalDateTime createdAt;

    @LastModifiedDate // 2. 마지막 변경 시점
    private LocalDateTime modifiedAt;
}
  1. 추상 클래스 설정 (abstract)
  2. 상속 받은 클래스의 멤버 변수 되도록 설정
  3. getter 메소드 자동 생성: 정보 받았을 때 조회하기 위해서 사용
@Getter // 6. get 함수를 자동 생성합니다.
@MappedSuperclass // 5. 멤버 변수가 컬럼이 되도록 합니다.
@EntityListeners(AuditingEntityListener.class) // 변경되었을 때 자동으로 기록합니다.
public abstract class Timestamped {	// 4. abstract 추가
    @CreatedDate // 최초 생성 시점
    private LocalDateTime createdAt;

    @LastModifiedDate // 마지막 변경 시점
    private LocalDateTime modifiedAt;
}

Application 수정하기

  1. 시간 자동 변경 기능 설정: JPA Timpstamped 기능 사용하기 위해 사용
@EnableJpaAuditing // 1. 시간 자동 변경이 가능하도록 합니다.
@SpringBootApplication // 스프링 부트임을 선언합니다.
public class Week04Application {
    public static void main(String[] args) {
        SpringApplication.run(Week04Application.class, args);
    }
}

Product 클래스 생성하기

  1. 멤버 변수 선언 (ID, 제목, 이미지, 링크, 최저가, 관심가격)
public class Product{
    private Long id;
    private String title;
    private String image;
    private String link;
    private int lprice;
    private int myprice;
}
  1. DB 테이블 설정
  2. DB 열 설정
  3. Timestamped 상속 설정 (extends)
@Entity // 2. DB 테이블 역할을 합니다.
public class Product extends Timestamped{	// 4. 상속

    // 3. ID가 자동으로 생성 및 증가합니다.
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Id
    private Long id;

    // 3. 반드시 값을 가지도록 합니다.
    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String image;

    @Column(nullable = false)
    private String link;

    @Column(nullable = false)
    private int lprice;

    @Column(nullable = false)
    private int myprice;
}
  1. 기본 생성자 생성
  2. getter 메소드 자동 생성
@Getter // 6. get 함수를 일괄적으로 만들어줍니다.
@NoArgsConstructor // 5. 기본 생성자를 만들어줍니다.
@Entity // DB 테이블 역할을 합니다.
public class Product extends Timestamped{

		// ID가 자동으로 생성 및 증가합니다.
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Id
    private Long id;

		// 반드시 값을 가지도록 합니다.
    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String image;

    @Column(nullable = false)
    private String link;

    @Column(nullable = false)
    private int lprice;

    @Column(nullable = false)
    private int myprice;
}

ProductRepository 인터페이스 생성하기

  1. JpaRepository 기능 추가
public interface ProductRepository extends JpaRepository<Product, Long> {	// 1. JPA 추가
}

ProductRestController 클래스 생성하기

  1. RestController 선언: CRUD 요청을 JSON 형시으로 자동 응답하기 위해 사용
@RestController // 1. JSON으로 데이터를 주고받음을 선언합니다.
public class ProductRestController {
}
  1. GetMapping 설정 (/api/products)
  2. getProducts 메소드 생성
  3. productRepository 이용하여 찾는 기능 설정
@RestController // JSON으로 데이터를 주고받음을 선언합니다.
public class ProductRestController {

    ProductRepository productRepository;	// 4. productRepository 선언

    // 등록된 전체 상품 목록 조회
    @GetMapping("/api/products")	// 2. GetMapping 설정
    public List<Product> getProducts() {	// 3. getProducts 메소드 생성
        return productRepository.findAll();	// 4. productRepository 이용하여 찾는 기능 설정
    }
}
  1. RestController에게 Repository가 꼭 필요한 것임을 알려서 자동으로 생성되도록 설정 (RequiredArgsConstructor, final 한쌍을 이룸)
@RequiredArgsConstructor // 5. final로 선언된 멤버 변수를 자동으로 생성합니다.
@RestController // JSON으로 데이터를 주고받음을 선언합니다.
public class ProductRestController {

    private final ProductRepository productRepository;	// 5. final 추가

    // 등록된 전체 상품 목록 조회
    @GetMapping("/api/products")
    public List<Product> getProducts() {
        return productRepository.findAll();
    }
}

ARC 정상 동작 확인하기

  1. GET -> /api/products -> 상태: 200 확인
profile
개발일지

0개의 댓글