Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Week1 step3 #724

Open
wants to merge 18 commits into
base: sanghou
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/main/java/subway/SubwayExceptionHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package subway;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class SubwayExceptionHandler {

@ExceptionHandler(value = IllegalArgumentException.class)
public ResponseEntity<Void> handleIllegalStateException(IllegalArgumentException error) {
return ResponseEntity.badRequest().build();
}

@ExceptionHandler(value = IllegalStateException.class)
public ResponseEntity<Void> handleIllegalStateException(IllegalStateException error) {
return ResponseEntity.badRequest().build();
}
Comment on lines +10 to +18
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외 처리 핸들러를 만드셨네요 👍
그런데 IllegalArgumentException과 IllegalStateException이 같은 동작을 하고 있네요.
두 예외의 차이점이 뭘까요?

}
43 changes: 19 additions & 24 deletions src/main/java/subway/line/Line.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package subway.line;

import javax.persistence.CascadeType;
import java.util.List;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import subway.section.Section;
import subway.sections.Sections;
import subway.station.Station;

@Entity
Expand All @@ -19,23 +21,15 @@ public class Line {

private String color;

@ManyToOne(cascade = CascadeType.ALL)
private Station upStation; // 상행역

@ManyToOne(cascade = CascadeType.ALL)
private Station downStation; // 하행역

private Long distance;
@Embedded
private Sections sections;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이런 컬렉션(with 일급 컬렉션)자료는 필드 초기화를 해주면 NPE에서 좀 더 자유로워 질 수 있습니다 ㅎㅎ


public Line() {}

public Line(String name, String color, Station upStation, Station downStation,
Long distance) {
public Line(String name, String color) {
this.name = name;
this.color = color;
this.upStation = upStation;
this.downStation = downStation;
this.distance = distance;
this.sections = new Sections();
}

public Long getId() {
Expand All @@ -46,25 +40,26 @@ public String getName() {
return name;
}

public Station getUpStation() {
return upStation;
}

public Station getDownStation() {
return downStation;
}

public String getColor() {
return color;
}

public Long getDistance() {
return distance;
public List<Station> getStations() {
return sections.getStations();
}

public Line updateLine(String name, String color) {
this.name = name;
this.color = color;
return this;
}

public Line addSection(Section add) {
sections.addSection(add);
return this;
}

public void removeSection(Station downStation) {
sections.removeSection(downStation);
}
}
19 changes: 6 additions & 13 deletions src/main/java/subway/line/LineController.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,17 @@ public LineController(LineService lineService) {

/**
* 새로운 지하철 노선을 추가한다.
* @param request LineCreateRequest
* @param request
* @return 노선 생성의 결과를 반환한다.
*/
@PostMapping("/lines")
public ResponseEntity<LineResponse> createLine(@RequestBody LineCreateRequest request) {
return ResponseEntity.ok().body(lineService.saveLine(
request.getName(),
request.getColor(),
request.getUpStationId(),
request.getDownStationId(),
request.getDistance()
)
);
return ResponseEntity.ok().body(lineService.saveLine(request));
}

/**
* 지하철의 노선을 조회한다
* @param id Long. 조회하려는 노선의 ID
* @param id 조회하려는 노선의 ID
* @return 지하철 노선의 조회 결과 값을 반환한다.
*/
@GetMapping("/lines/{id}")
Expand All @@ -53,7 +46,7 @@ public ResponseEntity<LineResponse> showLine(@PathVariable Long id) {

/**
* 모든 지하철의 노선을 조회한다.
* @return 모든 지하철 모든의 정보를 반환한다.
* @return 모든 지하철 노선 정보를 반환한다.
*/
@GetMapping("/lines")
public ResponseEntity<List<LineResponse>> showAllLines() {
Expand All @@ -62,7 +55,7 @@ public ResponseEntity<List<LineResponse>> showAllLines() {

/**
* 특정 지하철 노선의 정보를 변경한다.
* @param id Long. 변경하려는 지하철 노선의 ID
* @param id 변경하려는 지하철 노선의 ID
* @param request
* @return 변환된 지하철 정보를 반환한다. 존재하지 않는 지하철 노선에 대한 변경은 noContent()를 반환한다.
*/
Expand All @@ -77,7 +70,7 @@ public ResponseEntity<LineResponse> patchLine(@PathVariable Long id, @RequestBod

/**
* id에 해당하는 노선 정보를 삭제한다.
* @param id Long. 삭제하려는 노선의 ID
* @param id 삭제하려는 노선의 ID
* @return noContent() 결과값
*/
@DeleteMapping("/lines/{id}")
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/subway/line/LineCreateRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

public class LineCreateRequest {

private String name;
private String color;
private Long upStationId;
private Long downStationId;
private Long distance;
private final String name;
private final String color;
private final Long upStationId;
private final Long downStationId;
private final Long distance;

public String getName() {
return name;
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/subway/line/LinePatchRequest.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package subway.line;

public class LinePatchRequest {
private String name;
private String color;
private final String name;
private final String color;

public LinePatchRequest(String name, String color) {
this.name = name;
Expand Down
40 changes: 20 additions & 20 deletions src/main/java/subway/line/LineResponse.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
package subway.line;

import java.util.List;
import java.util.stream.Collectors;
import subway.station.Station;
import subway.station.StationResponse;

public class LineResponse {

private Long id;
private String name;
private String color;
private Station upStation;
private Station downStation;
private Long distance;
private final Long id;
private final String name;
private final String color;
private final List<StationResponse> stations;

public LineResponse(Long id, String name, String color, Station upStation, Station downStation, Long distance) {
public LineResponse(Long id, String name, String color, List<Station> stations) {
this.id = id;
this.name = name;
this.color = color;
this.upStation = upStation;
this.downStation = downStation;
this.distance = distance;
this.stations = stations.stream().map(s -> new StationResponse(s.getId(), s.getName())).collect(Collectors.toList());
}

public static LineResponse from(Line line) {
return new LineResponse(
line.getId(),
line.getName(),
line.getColor(),
line.getStations()
);
}

public Long getId() {
Expand All @@ -32,15 +40,7 @@ public String getColor() {
return color;
}

public Station getUpStation() {
return upStation;
}

public Station getDownStation() {
return downStation;
}

public Long getDistance() {
return distance;
public List<StationResponse> getStations() {
return stations;
}
}
55 changes: 38 additions & 17 deletions src/main/java/subway/line/LineService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,44 @@
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import subway.section.Section;
import subway.section.SectionCreateRequest;
import subway.section.SectionRepository;
import subway.section.SectionResponse;
import subway.station.Station;
import subway.station.StationRepository;
import subway.station.StationService;

@Service
public class LineService {

private final LineRepository lineRepository;
private final StationRepository stationRepository;
private final StationService stationService;
private final SectionRepository sectionRepository;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 순환참조가 발생하셨군요 🤔
제 생각에는 해당 리포지토리를 지울 수 있을 것 같아요!


public LineService(LineRepository repository, StationRepository stationRepository) {
public LineService(LineRepository repository, StationService stationService, SectionRepository sectionRepository) {
this.lineRepository = repository;
this.stationRepository = stationRepository;
this.stationService = stationService;
this.sectionRepository = sectionRepository;
}

@Transactional
public LineResponse saveLine(String name, String color, Long upStationId, Long downStationId, Long distance) {
Optional<Station> inbound = stationRepository.findById(upStationId);
Optional<Station> outbound = stationRepository.findById(downStationId);
Line created = lineRepository.save(new Line(name, color, inbound.get(), outbound.get(), distance));
return createServiceResponse(created);
public LineResponse saveLine(LineCreateRequest request) {
Station upStation = stationService.findById(request.getUpStationId());
Station downStation = stationService.findById(request.getDownStationId());

Line created = lineRepository.save(new Line(request.getName(), request.getColor()));
createSection(created.getId(), new SectionCreateRequest(upStation.getId(), downStation.getId(), request.getDistance()));

return LineResponse.from(created);
Comment on lines +30 to +36
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고민하셨던 부분이 여기군요!
이 부분에 대해 코멘트 남겨드렸으니 확인해주세요!

}

public Optional<LineResponse> showLine(Long id) {
Optional<Line> optionalLine = lineRepository.findById(id);

return optionalLine.map(this::createServiceResponse);
return lineRepository.findById(id).map(LineResponse::from);
}

public List<LineResponse> showLines() {
return lineRepository.findAll().stream()
.map(this::createServiceResponse)
.map(LineResponse::from)
.collect(Collectors.toList());
}

Expand All @@ -47,11 +54,25 @@ public Optional<LineResponse> updateLine(Long id, String name, String color) {
Optional<Line> optionalLine = lineRepository.findById(id);

return optionalLine.map(line -> line.updateLine(name, color))
.map(lineRepository::save)
.map(this::createServiceResponse);
.map(line -> LineResponse.from(lineRepository.save(line)));
}

@Transactional
public SectionResponse createSection(Long lineId, SectionCreateRequest request) {
Station upStation = stationService.findById(request.getUpStationId());
Station downStation = stationService.findById(request.getDownStationId());
Line line = lineRepository.findById(lineId).orElseThrow(IllegalArgumentException::new);

Section created = sectionRepository.save(new Section(upStation, downStation, request.getDistance()));

lineRepository.save(line.addSection(created));

return SectionResponse.from(created);
}

private LineResponse createServiceResponse(Line line) {
return new LineResponse(line.getId(), line.getName(), line.getColor(), line.getUpStation(), line.getDownStation(), line.getDistance());
public void removeSection(Long lineId, Long downStationId) {
Line line = lineRepository.findById(lineId).orElseThrow(IllegalArgumentException::new);
Station station = stationService.findById(downStationId);
line.removeSection(station);
}
}
58 changes: 58 additions & 0 deletions src/main/java/subway/section/Section.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package subway.section;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import subway.station.Station;

@Entity
public class Section {

@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
private Station upStation;

@ManyToOne
private Station downStation;

private Long distance;

public Long getId() {
return id;
}

// 상행역
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

불필요한 주석은 제거해주세요!

public Station getUpStation() {
return upStation;
}

// 하행역
public Station getDownStation() {
return downStation;
}

public Long getDistance() {
return distance;
}

public Section() {}

public Section(Station upStation, Station downStation, Long distance) {
this.upStation = upStation;
this.downStation = downStation;
this.distance = distance;
}

@Override
public String toString() {
return String.format("[Section id : %d, upStationId : %d, downStationId: %d]",
id,
upStation.getId(),
downStation.getId()
);
}
}
Loading