From 89d224f5675f6402f3bb9c23368488a12cc09f95 Mon Sep 17 00:00:00 2001 From: bingseok Date: Mon, 19 May 2025 16:13:53 +0900 Subject: [PATCH] =?UTF-8?q?Refactor:=20arsId=20=EC=A4=91=EB=B3=B5=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/bus/entity/BusStation.java | 2 +- .../bus/repository/BusStationRepository.java | 3 ++ .../handler/LocationWebSocketHandler.java | 29 +++++++++++++------ 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/main/java/server/gooroomi/domain/bus/entity/BusStation.java b/src/main/java/server/gooroomi/domain/bus/entity/BusStation.java index d2e45db..bf8a214 100644 --- a/src/main/java/server/gooroomi/domain/bus/entity/BusStation.java +++ b/src/main/java/server/gooroomi/domain/bus/entity/BusStation.java @@ -28,7 +28,7 @@ public class BusStation extends BaseTimeEntity { @JoinColumn(name = "user_id") private User user; - @OneToMany(mappedBy = "busStation", cascade = CascadeType.ALL, orphanRemoval = true) + @OneToMany(mappedBy = "busStation", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) private List busArrivals = new ArrayList<>(); @Builder diff --git a/src/main/java/server/gooroomi/domain/bus/repository/BusStationRepository.java b/src/main/java/server/gooroomi/domain/bus/repository/BusStationRepository.java index ab803ab..fa18425 100644 --- a/src/main/java/server/gooroomi/domain/bus/repository/BusStationRepository.java +++ b/src/main/java/server/gooroomi/domain/bus/repository/BusStationRepository.java @@ -4,6 +4,9 @@ import org.springframework.stereotype.Repository; import server.gooroomi.domain.bus.entity.BusStation; +import java.util.Optional; + @Repository public interface BusStationRepository extends JpaRepository { + Optional findByUserId(Long userId); } diff --git a/src/main/java/server/gooroomi/global/handler/LocationWebSocketHandler.java b/src/main/java/server/gooroomi/global/handler/LocationWebSocketHandler.java index 8d5e058..8678ff3 100644 --- a/src/main/java/server/gooroomi/global/handler/LocationWebSocketHandler.java +++ b/src/main/java/server/gooroomi/global/handler/LocationWebSocketHandler.java @@ -7,6 +7,7 @@ import org.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; @@ -26,6 +27,7 @@ import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.IntStream; @@ -56,6 +58,7 @@ public void afterConnectionEstablished(WebSocketSession session) throws Exceptio // 클라이언트로부터 메시지를 수신했을 때 호출됨 (위/경도 기반 처리) @Override + @Transactional protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // JSON 메시지를 DTO로 변환 LocationDto latLng = objectMapper.readValue(message.getPayload(), LocationDto.class); @@ -67,6 +70,7 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) // 사용자 위치 업데이트 user.updateLocation(latLng.getLatitude(), latLng.getLongitude()); + userRepository.save(user); // 사용자 위치 기반으로 가장 가까운 정류장 조회 String stationJson = stationInfoApiClient.getNearbyStations(latLng.getLongitude(), latLng.getLatitude(), searchRadius); @@ -89,13 +93,6 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) JSONObject arrivalRoot = new JSONObject(arrivalJson); JSONArray arrivalList = arrivalRoot.getJSONObject("msgBody").optJSONArray("itemList"); - // 정류장 생성 후 사용자에 할당 - BusStation busStation = BusConverter.toBusStation(arsId, stationNm); - busStation.assignUserBusStation(user); - - // 기존 도착 정보 초기화 - busStation.getBusArrivals().clear(); - // 도착 예정 버스 목록 중 120초 이내 도착하는 버스를 필터링하여 엔티티로 변환 List busArrivals = IntStream.range(0, arrivalList.length()) .mapToObj(i -> { @@ -106,13 +103,27 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) int seconds = Integer.parseInt(arrivalTime); if ("운행종료".equals(arrmsg1) || "출발대기".equals(arrmsg1) || seconds > 120) return null; BusArrival busArrival = BusConverter.toBusArrival(busNumber, arrivalTime); - busArrival.assignBusStation(busStation); return busArrival; }) .filter(Objects::nonNull) .toList(); - // 정류장에 도착 버스 리스트 추가 및 저장 (cascade로 BusArrivals도 같이 저장됨) + Optional existing = busStationRepository.findByUserId(user.getId()); + + BusStation busStation; + if (existing.isPresent()) { + // 기존 정류장 update + busStation = existing.get(); + busStation.updateBusStationInfo(arsId, stationNm); + busStation.getBusArrivals().clear(); + } else { + // 새로 생성 + busStation = BusConverter.toBusStation(arsId, stationNm); + busStation.assignUserBusStation(user); + } + + // 버스 도착 정보 추가 + busArrivals.forEach(arrival -> arrival.assignBusStation(busStation)); busStation.getBusArrivals().addAll(busArrivals); busStationRepository.save(busStation);