@@ -153,17 +153,40 @@ public void importStocksFromJson(String jsonFilePath) {
153153 }
154154 }
155155
156- // 새 종목 저장
156+ // 새 종목 저장 - 개별 처리로 중복 ID 방지
157157 if (!newStocks .isEmpty ()) {
158- try {
159- entityManager .flush ();
160- stockRepository .saveAll (newStocks );
161- entityManager .flush ();
162- log .info ("Saved {} new stocks" , newStocks .size ());
163- } catch (Exception e ) {
164- log .error ("Error saving new stocks: {}" , e .getMessage ());
165- throw e ;
158+ int savedCount = 0 ;
159+ int skippedCount = 0 ;
160+ for (Stock stock : newStocks ) {
161+ try {
162+ // symbol로 이미 존재하는지 다시 확인 (DB에서 직접 확인)
163+ Optional <Stock > existingStock = stockRepository .findBySymbol (stock .getSymbol ());
164+ if (existingStock .isPresent ()) {
165+ // 이미 존재하면 업데이트로 처리
166+ Stock existing = existingStock .get ();
167+ existing .updateSymbolNameIfNull (stock .getSymbolName ());
168+ existing .setValid (true );
169+ if (stock .getDomesticSector () != null ) {
170+ existing .setDomesticSector (stock .getDomesticSector ());
171+ }
172+ if (stock .getOverseasSector () != null ) {
173+ existing .setOverseasSector (stock .getOverseasSector ());
174+ }
175+ stockRepository .save (existing );
176+ skippedCount ++;
177+ log .debug ("Stock already exists, updated: {}" , stock .getSymbol ());
178+ } else {
179+ // 새 종목 저장
180+ stockRepository .save (stock );
181+ savedCount ++;
182+ }
183+ } catch (Exception e ) {
184+ log .warn ("Failed to save stock: {} - {}" , stock .getSymbol (), e .getMessage ());
185+ skippedCount ++;
186+ }
166187 }
188+ entityManager .flush ();
189+ log .info ("Saved {} new stocks, {} skipped (already exists or error)" , savedCount , skippedCount );
167190 }
168191
169192 // 기존 종목 업데이트 - 개별 처리로 안전하게
0 commit comments