posted by 구로공돌이 2025. 9. 2. 15:17

package com.example.demo.service;

import com.example.demo.dto.ProductRequestDto;
import com.example.demo.exception.DataTooLongException;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets; // UTF-8을 위해 import 합니다.
// ... other imports

@Service
public class ProductService {

    // ... Autowired repository

    // DB 컬럼의 실제 최대 바이트 크기를 상수로 정의합니다.
    private static final int MAX_BYTES_LIMIT = 4000;

    public void saveProduct(ProductRequestDto requestDto) {
        String description = requestDto.getDescription();

        // description 필드가 null이 아닌 경우에만 바이트 길이를 체크합니다.
        if (description != null) {
            // 문자열을 UTF-8 바이트 배열로 변환하고, 그 길이를 확인합니다.
            int byteLength = description.getBytes(StandardCharsets.UTF_8).length;

            if (byteLength > MAX_BYTES_LIMIT) {
                // 예외를 발생시켜 저장을 중단하고, 사용자에게 명확한 경고 메시지를 전달합니다.
                throw new DataTooLongException(
                    "제품 설명이 최대 허용 크기를 초과했습니다. (현재 크기: " + byteLength + " / 최대 " + MAX_BYTES_LIMIT + " 바이트)"
                );
            }
        }

        // 유효성 검증을 통과한 경우에만 저장 로직을 수행합니다.
        // YourEntity entity = new YourEntity();
        // entity.setDescription(description);
        // productRepository.save(entity);

        System.out.println("데이터 저장 성공!");
    }
}