티스토리 뷰
728x90
반응형
들어가기 전에
5주차에 JPA 기본 세팅을 했다. 세팅하는 방법과 DB설치는 아래 사이트에서 확인 해보면된다.
https://jih3508.tistory.com/168
[JSCODE-스프링부트 입문] 5주차
데이터베이스 면접 단골질문 데이터베이스의 특징에 대해 설명해주세요. 실시간 접근성 생성, 수정, 삭제를 통한 최신 데이터 유지 사용자들 간의 동시 공유 사용자가 원하는 데이터를 주소가
jih3508.tistory.com
(예제) Product 등록, 조회 api
이번에 JPA를 하는지 어떻게 상품 데이터를 가지고 보여줄 예정이다.
Product.java
product 테이블에 매핑할 객체를 만든다.
import lombok.Data;
import lombok.ToString;
import javax.persistence.*;
@Table(name = "product", schema = "test")
@Entity
@Data
@ToString
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column
private Long price;
public Product() {
}
}
ProductRepository.java
Spring JPA data 사용하기 위해서 JPA Repository를 만들것이다.
import com.example.test.storage.model.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
ProductController.java
import com.example.test.storage.model.entity.Product;
import com.example.test.storage.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/product")
public class ProductController {
@Autowired
ProductService productService;
@GetMapping("")
public List<Product> findAll(){
return productService.findAll();
}
@PostMapping("")
public String saveProduct(Product product){
productService.save(product);
return product.toString() + "\n저장하였습니다";
}
}
ProductService.java
Spring JPA Data에 기본으로 findAll을 제공한다.
import com.example.test.storage.model.entity.Product;
import com.example.test.storage.repository.ProductRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public List<Product> findAll(){
return productRepository.findAll();
}
public void save(Product product){
productRepository.save(product);
}
}
결과
등록
전체 조회
상품 상세조회 구현하기
ProductRepository.java
findAllById를 사용하면 Id를 자동으로 조회 한다.
import com.example.test.storage.model.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
Product findAllById(Long id);
}
ProductService.java
리턴하면 Optional 타입으로 반환한다.
public Product findById(Long id){
return productRepository.findById(id)
.map(product -> product)
.orElseGet(() -> null);
}
ProductController.java
상품이 있을때와 없을때를 구분해서 처리한다.
@GetMapping("{id}")
public Object findById(@PathVariable(value = "id") Long id) throws Exception {
Product product = productService.findById(id);
if(product == null){
return "조회할 데이터 없습니다.";
}
return product;
}
결과
(심화) 이름으로 상품 상세조회 구현하기
ProductRepository.java
JPA에서 쿼리를 직접 짜서 조회하도록 한다.
@Query("SELECT P FROM Product P WHERE P.name LIKE %:name%")
List<Product> findByAllName(String name);
ProductController.java
findAll 메도드에서 분기 처리한다.
@GetMapping("")
public List<Product> findAll(@RequestParam(name = "name", required = false) String name){
if(name == null || name.isEmpty()){
return productService.findAll();
}
return productService.findByAllName(name);
}
결과
(심화) 요구사항 만족하는 상품 조회 메소드 구현하기
ProductRepository.java
@Query("SELECT P FROM Product P WHERE P.name LIKE %:name% AND P.price = :price")
List<Product> findAllByNameAndPrice(String name, long price);
ProductController.java
findAll 메도드에서 분기 처리한다.
@GetMapping("")
public List<Product> findAll(@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "price", required = false) Long price){
if(name == null || name.isEmpty()){
return productService.findAll();
}else if(price == null){
return productService.findByAllName(name);
}
return productService.findAllByNameAndPrice(name, price);
}
결과
마무리
전체 코드는 아래에서 참조 하면된다.
https://github.com/JSCODE-EDU/spring_class_IkHyun/tree/feature/ikhyun/6%ED%9A%8C%EC%B0%A8
728x90
반응형
'Spring-boot > Spring Study 기록 일지' 카테고리의 다른 글
[JSCODE-백엔드 입문 프로젝트 클래스(Spring Boot)] 3주 (0) | 2023.05.22 |
---|---|
[JSCODE-백엔드 입문 프로젝트 클래스(Spring Boot)] 1주 (0) | 2023.05.09 |
[JSCODE-스프링부트 입문] 5주차 (0) | 2023.03.24 |
[JSCODE-스프링부트 입문] 4주차 (0) | 2023.03.19 |
[JSCODE-스프링부트 입문] 3주차 (0) | 2023.03.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 누적합
- 자바
- 동적 계획법
- spring-boot
- DFS
- 백준
- 문자열
- 구현
- Programmerse
- 그래프
- BaekJoon
- DP
- 동적계획법
- 이론
- 재귀호출
- level2
- 파이썬
- 알고리즘
- 그리디
- BFS
- LeetCode
- 조합
- 배열
- java
- Greedy
- JSCODE
- 넓이 우선 탐색
- Python
- 백트레킹
- 수학
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함