study/spring | java

[Select Shop] 셀렉샵 만들기 5. 관심 상품 조회하기

_드레 2021. 6. 6. 19:57

src > main > java > com.xxx.xxx > models 패키지 생성 > Timestamped 클래스 생성

[Timestamped.java 클래스]

@Getter //get 함수 자동 생성
@MappedSuperclass //멤버 변수가 컬럼이 되도록 함
// ↑ createAt과 modifiedAt이, 상속한 클래스의 멤버변수가 되도록 만들어줌
@EntityListeners(AuditingEntityListener.class) //변경되었을 때 자동으로 기록
public abstract class Timestamped {
    @CreatedDate // 최초 생성 시점
    private LocalDateTime createdAt;

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

 


 

 

[Week04Application 수정] - @EnableJpaAuditing추가 

@EnableJpaAuditing // 시간 자동 변경
@SpringBootApplication // 스프링 부트임을 선언
public class Week04Application {
    public static void main(String[] args) {
        SpringApplication.run(Week04Application.class, args);
    }
}

 


 

src > main > java > com.xxx.xxx > models > Product 클래스 생성

[Product.java 클래스]

@Getter 
@NoArgsConstructor // 기본 생성자
@Entity // DB 테이블 역할
public class Product extends Timestamped{

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

    // 반드시 값을 가지도록 nullable = false
    @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;
    //사용자가 설정(요구)하는 최저가 저장하기
}

 


 

src > main > java > com.xxx.xxx > models  > ProductRepository 인터페이스 생성

[ProductRepository.java 인터페이스]

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

extends : 상속 JpaRepository 기능을 사용 

 


 

src > main > java > com.xxx.xxx > controller 패키지 생성 > ProductRestController 클래스 생성

[ProductRepository.java 인터페이스]

@RequiredArgsConstructor // final로 선언된 멤버 변수를 자동으로 생성
@RestController // JSON으로 데이터를 주고받음
public class ProductRestController {

    private final ProductRepository productRepository;

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

@RestController : JSON으로 응답하는 자동응답기 ~

@GetMapping : get방식으로 ("/api/products") 라는 이름으로 요청 올 것

 

public 반환형 메소드명 (재료) 

반환형 : product의 목록

 

productRepository가 뭔지 모르니까 productRepository 멤버변수 선언 해줌 

rest controller에게 꼭 필요하다는걸 알려주기 : final 

 

 


 

* ARC로 테스트 

빈 배열이 잘 나옴 (200OK)