260311_01_ENH: JDBC Template 기반 Bulk Insert로 교체 및 디스크 기반 엑셀 스트림 리더 적용

This commit is contained in:
2026-03-11 16:22:24 +09:00
parent ad1c445f5b
commit a30f7d09d4
10 changed files with 466 additions and 101 deletions

View File

@@ -1,33 +1,33 @@
package com.kri.lge.penetration.service;
import static com.kri.lge.penetration.common.consts.LgePenetrationConst.INSERT_CHUNK_SIZE;
import static com.kri.lge.penetration.common.consts.LgePenetrationConst.EXCEL_ID;
import static com.kri.lge.penetration.common.consts.LgePenetrationConst.INSERT_CHUNK_SIZE;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kri.common.datetime.DateTimeUtil;
import com.kri.common.excel.ExcelMapper;
import com.kri.common.web.BusinessException;
import com.kri.lge.penetration.dto.DataItemDto;
import com.kri.lge.penetration.dto.ExcelUploadResultDto;
import com.kri.lge.penetration.persistence.entity.TDataEntity;
import com.kri.lge.penetration.persistence.repository.DataRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import com.kri.lge.penetration.persistence.jdbc.DataJdbcRepository;
import com.kri.lge.penetration.persistence.jdbc.DataJdbcRepository.TDataBatchInsertResult;
import com.kri.lge.penetration.persistence.jdbc.DataJdbcRepository.TDataInsertFailure;
import com.kri.lge.penetration.persistence.jdbc.DataJdbcRepository.TDataInsertRow;
import com.kri.lge.penetration.service.file.DataFileService;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@Log4j2
@@ -35,58 +35,51 @@ import org.springframework.web.multipart.MultipartFile;
@RequiredArgsConstructor
public class UploadService {
@PersistenceContext
private EntityManager em;
private final DataFileService dataFileService;
private final ObjectMapper objectMapper;
private final DataRepository dataRepository;
private final DataJdbcRepository tDataJdbcRepository;
public ExcelUploadResultDto uploadData(MultipartFile file){
try (InputStream in = file.getInputStream()) {
List<RowContext> buffer = new ArrayList<>(INSERT_CHUNK_SIZE);
List<Map<String, String>> failRows = new ArrayList<>();
@Transactional
public ExcelUploadResultDto uploadData(MultipartFile file) {
Path dataFilePath = dataFileService.saveListFile(file);
AtomicInteger total = new AtomicInteger();
AtomicInteger success = new AtomicInteger();
AtomicInteger fail = new AtomicInteger();
List<RowContext> buffer = new ArrayList<>(INSERT_CHUNK_SIZE);
List<Map<String, String>> failRows = new ArrayList<>();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
final String regUser = "system";
AtomicInteger total = new AtomicInteger();
AtomicInteger success = new AtomicInteger();
AtomicInteger fail = new AtomicInteger();
ExcelMapper.readStreaming(in, (row, rowIndex) -> {
total.incrementAndGet();
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
final String regUser = "system";
ParsedRow parsed = parseRowToEntity(row, regUser, now);
if (parsed.reason != null) {
fail.incrementAndGet();
failRows.add(buildFailRow(row, rowIndex, parsed.reason));
return;
}
ExcelMapper.readStreaming(dataFilePath, (row, rowIndex) -> {
total.incrementAndGet();
buffer.add(new RowContext(rowIndex, row, parsed.entity));
ParsedRow parsed = parseRow(row, regUser, now);
if (parsed.reason != null) {
fail.incrementAndGet();
failRows.add(buildFailRow(row, rowIndex, parsed.reason));
return;
}
if (buffer.size() >= INSERT_CHUNK_SIZE) {
flushBuffer(buffer, success, fail, failRows);
}
});
buffer.add(new RowContext(rowIndex, row, parsed.insertRow));
if (!buffer.isEmpty()) {
if (buffer.size() >= INSERT_CHUNK_SIZE) {
flushBuffer(buffer, success, fail, failRows);
}
});
byte[] errorFile = null;
boolean hasErrorFile = !failRows.isEmpty();
if (hasErrorFile) {
errorFile = toXlsx(failRows);
}
return ExcelUploadResultDto.of(total.get(), success.get(), fail.get(), errorFile);
} catch (IOException ex){
throw BusinessException.badRequest("CAN_NOT_OPEN", "파일 스트림을 열 수 없습니다.")
.with("fileName",file.getOriginalFilename())
.with("errorMessage",ex.getMessage());
if (!buffer.isEmpty()) {
flushBuffer(buffer, success, fail, failRows);
}
byte[] errorFile = null;
if (!failRows.isEmpty()) {
errorFile = toXlsx(failRows);
}
return ExcelUploadResultDto.of(total.get(), success.get(), fail.get(), errorFile);
}
private void flushBuffer(
@@ -95,29 +88,30 @@ public class UploadService {
AtomicInteger fail,
List<Map<String, String>> failRows
) {
try {
List<TDataEntity> entities = buffer.stream().map(rc -> rc.entity).toList();
if (buffer.isEmpty()) {
return;
}
dataRepository.saveAll(entities);
success.addAndGet(buffer.size());
} catch (DataAccessException e) {
// 배치가 한 번에 터지면, 개별 저장으로 폴백해서 "어느 행이 문제인지" 잡는다
for (RowContext rc : buffer) {
try {
dataRepository.saveAndFlush(rc.entity);
success.incrementAndGet();
} catch (DataAccessException ex) {
fail.incrementAndGet();
failRows.add(buildFailRow(rc.rawRow, rc.rowIndex, "DB 저장 실패: " + rootMessage(ex)));
}
try {
List<TDataInsertRow> rows = buffer.stream()
.map(RowContext::insertRow)
.toList();
TDataBatchInsertResult result = tDataJdbcRepository.bulkInsert(rows);
success.addAndGet(result.successCount());
for (TDataInsertFailure failure : result.failures()) {
RowContext rc = buffer.get(failure.index());
fail.incrementAndGet();
failRows.add(buildFailRow(rc.rawRow(), rc.rowIndex(), "DB 저장 실패: " + failure.reason()));
}
} finally {
em.clear();
buffer.clear();
}
}
private ParsedRow parseRowToEntity(
private ParsedRow parseRow(
Map<String, String> row,
String regUser,
LocalDateTime regDt
@@ -126,7 +120,6 @@ public class UploadService {
return ParsedRow.fail("빈 행");
}
// sid
String sid = firstNonBlank(row.get(EXCEL_ID), row.get("sid"), row.get("SID"));
if (sid == null) {
return ParsedRow.fail("ID(sid) 누락");
@@ -135,21 +128,16 @@ public class UploadService {
return ParsedRow.fail("ID(sid) 길이 초과(>32): " + sid);
}
// rawData 구성
Map<String, List<DataItemDto>> rawData = new LinkedHashMap<>();
for (Map.Entry<String, String> e : row.entrySet()) {
String key = e.getKey();
if (key == null) continue;
// 제외
if (EXCEL_ID.equals(key)) continue;
//if (EXCEL_YEAR.equals(key)) continue;
//if (EXCEL_PRODUCT.equals(key)) continue;
String v = e.getValue();
if (v == null || v.isBlank()) {
continue; // 빈 값은 rawData에 안 넣음
continue;
}
Double s = parseDoubleLoose(v);
@@ -157,23 +145,33 @@ public class UploadService {
return ParsedRow.fail("숫자 파싱 실패: key=" + key + ", value=" + safe(v));
}
if(key.contains("#")){
key = key.substring(0,key.indexOf("#"));
if (key.contains("#")) {
key = key.substring(0, key.indexOf("#"));
}
rawData.computeIfAbsent(key, k -> new ArrayList<>()).add(DataItemDto.from(null, null, s));
rawData.computeIfAbsent(key, k -> new ArrayList<>())
.add(DataItemDto.from(null, null, s));
}
TDataEntity entity = new TDataEntity();
entity.setSid(sid);
entity.setRawData(rawData);
entity.setRegUser(regUser);
entity.setRegDt(regDt);
String rawDataJson;
try {
rawDataJson = objectMapper.writeValueAsString(rawData);
} catch (JsonProcessingException e) {
return ParsedRow.fail("rawData JSON 직렬화 실패: " + rootMessage(e));
}
return ParsedRow.ok(entity);
TDataInsertRow insertRow = new TDataInsertRow(
UUID.randomUUID().toString(),
sid,
rawDataJson,
regUser,
regDt
);
return ParsedRow.ok(insertRow);
}
private Map<String, String> buildFailRow(Map<String, String> row, int rowIndex, String reason) {
// 에러 엑셀에 행번호/사유를 앞에 고정 컬럼으로 넣고, 원본 컬럼들도 같이 싣는다
Map<String, String> m = new LinkedHashMap<>();
m.put("rowIndex", String.valueOf(rowIndex));
m.put("reason", reason);
@@ -195,26 +193,16 @@ public class UploadService {
private static String rootMessage(Throwable t) {
Throwable cur = t;
while (cur.getCause() != null) cur = cur.getCause();
return cur.getMessage();
}
private void doDebugLog(TDataEntity e){
try {
String json = objectMapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(e.getRawData());
log.info("rawDataJson={}", json);
} catch (JsonProcessingException ex) {
log.warn("rawData json serialize failed", ex);
while (cur.getCause() != null) {
cur = cur.getCause();
}
return cur.getMessage();
}
private static Double parseDoubleLoose(String s) {
if (s == null) return null;
String t = s.trim();
if (t.isEmpty()) return null;
// 천단위 콤마 제거
t = t.replace(",", "");
try {
return Double.parseDouble(t);
@@ -238,19 +226,19 @@ public class UploadService {
private record RowContext(
int rowIndex,
Map<String, String> rawRow,
TDataEntity entity
TDataInsertRow insertRow
) {}
private record ParsedRow(
TDataEntity entity,
TDataInsertRow insertRow,
String reason
) {
static ParsedRow ok(TDataEntity entity) {
return new ParsedRow(entity, null);
static ParsedRow ok(TDataInsertRow insertRow) {
return new ParsedRow(insertRow, null);
}
static ParsedRow fail(String reason) {
return new ParsedRow(null, reason);
}
}
}
}