JPA 예제 - (2)주문 조회 API GET

JAP란?
SQL 대신 자바로 DB와 상호작용하기 JPA(Java Persistence API)
지금까지는 JDBC를 활용하여 DAO 클래스에서 SQL쿼리를 통해 DB 작업을 하였는데요.//sql을 통한 회원가입 처리@Repositorypublic class UserDAO { @Autowired JdbcTemplate jdbcTemplate; // todo 회원가입 public int signUp(User
maeilcoding.tistory.com
JDBC 예제 - 유저관리 API GET id
https://maeilcoding.tistory.com/115 Controller, DAO, DTO 알아보기 // 예제 - 유저관리 API POSTDAO (Data Access Object) 란?데이터베이스나 기타 영속성 메커니즘에 접근하는 객체 목적: 데이터 접근 로직과 비즈니스
maeilcoding.tistory.com
// todo 2 getOrder
1. API 명세서 확인

2. Postman에 API Request 작성

3. Entity 클래스 변수 선언
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "`order`")
public class Order {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
public Long id;
@Column(length = 200)
public String productName;
@Column
public Integer quantity;
@Column
public Double totalPrice;
@Column
public Instant orderDate;
@PrePersist
public void prePersist(){
orderDate = Instant.now();
}
// 데이터 insert 할때 자동으로 현재시간이 들어감.
}
`order`로 백틱을 사용한 이유
@Table(name = "`order`")에서 백틱()을 사용하는 이유는 데이터베이스에서 order라는 이름이 SQL 예약어로 사용되기 때문입니다. SQL에서 ORDER BY와 같은 구문에서 ORDER`는 특정한 의미를 가지므로, 이를 테이블 이름으로 사용할 경우 충돌이 발생할 수 있습니다. orders와 같이 복수형으로 테이블 이름을 설정하는 것이 좋습니다.
4. Repository extends
@Repository
public interface OrderRepository extends JpaRepository<Order,Long> {
}
JPA에서는 JpaRepository 인터페이스를 상속받는 Resporitory 클래스를 통해 DB와 상호작용 합니다.
상속받은 메서드를 통해 CRUD 작업이 가능합니다.
Service 클래스에 메서드 완성
// 오더 id 조회
public OrderResponse getOrder(long id) {
Optional<Order> order = orderRepository.findById(id);
if (order.isPresent()) {
//DTO 로 변환
OrderResponse orderResponse = new OrderResponse
(order.get().id, order.get().productName, order.get().quantity,
order.get().totalPrice,
order.get().orderDate.toString());
// order.get().orderDate.toString() : orderDate 를 String 으로 변환
return orderResponse;
} else {
throw new RuntimeException();
}
}
1. 메서드 선언:
public OrderResponse getOrder(long id)
id를 매개변수로 받아 해당 ID의 주문을 조회합니다.
OrderResponse 객체를 반환합니다.
2. 데이터베이스에서 주문 조회:
Optional<Order> order = orderRepository.findById(id);
JpaRepository의 findById 메서드를 사용하여 주문을 조회합니다.
결과는 Optional<Order> 타입으로 반환됩니다. // id결과가 있을수도 있고, 없을수도 있음
조회 결과 확인 및 처리:
if (order.isPresent()) {
// 주문이 존재하는 경우의 처리
} else {
// 주문이 존재하지 않는 경우의 처리
}
DTO 변환 및 반환:
OrderResponse orderResponse = new OrderResponse(
order.get().id,
order.get().productName,
order.get().quantity,
order.get().totalPrice,
order.get().orderDate.toString()
);
return orderResponse;
조회된 Order 엔티티의 데이터를 OrderResponse DTO로 변환합니다.
orderDate를 문자열로 변환하여 DTO에 포함시킵니다.
예외 처리:
throw new RuntimeException();
주문이 존재하지 않을 경우 RuntimeException을 발생시킵니다.
이 메서드는 주어진 ID로 주문을 조회하고, 존재하면 DTO로 변환하여 반환하며, 존재하지 않으면 예외를 발생시킵니다.
Controller 클래스에 메서드 완성
// 오더 id 조회
@GetMapping("/orders/{id}")
ResponseEntity<Object> getOrder(@PathVariable long id) {
try {
OrderResponse orderResponse = orderService.getOrder(id);
return ResponseEntity.status(200).body(orderResponse);
} catch (Exception e) {
return ResponseEntity.status(404).build();
//컨트롤러에서는 throw 를 사용하지 않고 return 을 사용함
}
}