본문 바로가기

코딩 나도 할 수 있다!!

2024.06.12 (수) 다시 CRUD 시작

이번 프로젝트에서 내가 담당한 부분이 쇼핑몰의 상품, 주문의 CRUD 작성이었다
일단 상품에 맞는 CRUD 작성을 먼저 하였다

 

@RestController
@RequestMapping("/products")
class ProductController(
    private val productService: ProductService
) {

    @GetMapping
    fun getProductList(
    ): ResponseEntity<Lsit<ProductResponse>> {
        return ResponseEntity.ok(productService.getProductList())
    }

    @GetMapping("/{productId}")
    fun getProduct(
        @PathVariable productId: Long
    ): ResponseEntity<ProductResponse> {
        return ResponseEntity.ok(productService.getProduct(productId))
    }

    @PostMapping
    fun createProduct(
        @RequestBody request: CreateProductRequest
    ): ResponseEntity<ProductResponse> {
        return ResponseEntity.ok(productService.createProduct(request))
    }

    @PutMapping("/{productId}")
    fun updateProduct(
        @PathVariable productId: Long, 
        @RequestBody request: UpdateProductRequest
    ): ResponseEntity<ProductResponse> {
        return ResponseEntity.ok(productService.updateProduct(productId, request))
    }

    @DeleteMapping("/{productId}")
    fun deleteProduct(
        @PathVariable productId: Long
    ): ResponseEntity<Unit> {
        return ResponseEntity.ok(productService.deleteProduct(productId))
    }
}

상품 전체 조회, 상세조회, 등록, 수정, 삭제가 들어가 있다

이제 이 정도는 쉽다고는 할 수 없지만 무리 없이 할 수 있다

DTO는 만들기는 했지만 적지 않겠다

다음은 Entity 부분이다

@Entity
@Table(name = "product")
class Product(

    @Column(name = "name")
    var name: String,

    @Column(name = "description")
    var description: String,

    @Column(name = "price")
    var price: Float,

    @Column(name = "created_at")
    var createdAt: LocalDateTime = LocalDateTime.now(),

    @Column(name = "imgs")
    var imgs: String,

    @OneToMany(mappedBy = "product", cascade = [CascadeType.ALL], orphanRemoval = true, fetch = FetchType.LAZY)
    var orders: MutableList<Order> = mutableListOf()
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null

    fun createOrder(order: Order) {
        orders.add(order)
    }

    fun deleteOrder(order: Order) {
        orders.remove(order)
    }
}

fun Product.toProductResponse(): ProductResponse = ProductResponse(
    id = id!!,
    name = name,
    description = description,
    price = price,
    createdAt = createdAt,
    imgs = imgs
)

imgs를 String으로 해놓은 이유는 일단 String으로 해두고 나중에 바꾸기 위해서다

그리고 Order과 Product에 연관관계를 맺어 주었다

 

다음은 Repository 부분이다

interface ProductRepository : JpaRepository<Product, Long> {
}

사실 이건 왜 쓰는지 잘 모르겠다 그냥 이렇게 쓰니까 쓴다
라고 지나가면 안 되니까 이건 찾아봐야겠다

다음인 Service 부분이다

@Service
class ProductService(
    private val productRepository: ProductRepository,
) {

    fun getProductEntity(productId:Long):Product{
        return productRepository.findByIdOrNull(productId)
            ?: throw RuntimeException("Product with ID $productId not found")
    }

    fun getProductList(): List<Response> {
        return productRepository.findAll().map { it.toProductResponse() }
    }

    fun getProduct(productId: Long): ProductResponse {
        val result = productRepository.findByIdOrNull(productId)
            ?: throw RuntimeException("Product with ID $productId not found")
        return result.toProductResponse()
    }

    @Transactional
    fun createProduct(request: CreateProductRequest): ProductResponse {
        return productRepository.save(
            Product(
                name = request.name,
                description = request.description,
                price = request.price,
                imgs = request.imgs
            )
        ).toProductResponse()
    }

    @Transactional
    fun updateProduct(productId: Long, request: UpdateProductRequest): ProductResponse {
        val result = productRepository.findByIdOrNull(productId)
            ?: throw RuntimeException("Product with ID $productId not found")

        result.name = request.name
        result.description = request.description
        result.price = request.price
        result.imgs = request.imgs
        return productRepository.save(result).toProductResponse()
    }

    @Transactional
    fun deleteProduct(productId: Long) {
        val result = productRepository.findByIdOrNull(productId)
            ?: throw RuntimeException("Product with ID $productId not found")
        return productRepository.delete(result)
    }
}

Exception 같은 경우는 아직 개발하지 않아 런타임으로 일단 해두었다
개발이 되면 갈아끼울 예정이다
내일은 주문에 대한 CRUD를 작성해 볼 것이다