-
Notifications
You must be signed in to change notification settings - Fork 1
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
location 테이블에 데이터 적재(1회성 테스트) #18
Open
pingu9
wants to merge
1
commit into
main
Choose a base branch
from
feat-dj-location-code-initial-insert
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
package com.catcher.core; | ||
|
||
import com.opencsv.CSVParserBuilder; | ||
import com.opencsv.CSVReader; | ||
import com.opencsv.CSVReaderBuilder; | ||
import com.opencsv.bean.CsvBindByPosition; | ||
import com.opencsv.bean.CsvToBeanBuilder; | ||
|
||
import java.io.FileInputStream; | ||
import java.io.IOException; | ||
import java.io.InputStreamReader; | ||
import java.util.List; | ||
|
||
class CsvReader { | ||
|
||
public <T> List<T> readCSVFile(String filePath, char separator, String charset, Class<T> clazz) throws IOException { | ||
try (CSVReader csvReader = new CSVReaderBuilder(new InputStreamReader(new FileInputStream(filePath), charset)) | ||
.withCSVParser(new CSVParserBuilder() | ||
.withSeparator(separator) | ||
.build()) | ||
.withSkipLines(1) | ||
.build()) { | ||
List<T> csvDataList = new CsvToBeanBuilder<T>(csvReader) | ||
.withType(clazz) | ||
.build() | ||
.parse(); | ||
|
||
return csvDataList; | ||
} | ||
} | ||
|
||
public static class CsvDataWithNumber { | ||
|
||
@CsvBindByPosition(position = 0) | ||
private String areaCode; | ||
|
||
@CsvBindByPosition(position = 5) | ||
private String latitude; | ||
|
||
@CsvBindByPosition(position = 6) | ||
private String longitude; | ||
|
||
@CsvBindByPosition(position = 7) | ||
private String type; | ||
|
||
public String getAreaCode() { | ||
return areaCode; | ||
} | ||
|
||
public String getLatitude() { | ||
return latitude; | ||
} | ||
|
||
public String getLongitude() { | ||
return longitude; | ||
} | ||
|
||
public String getType() { | ||
return type; | ||
} | ||
|
||
} | ||
|
||
public static class MyCSVData { | ||
|
||
@CsvBindByPosition(position = 0) | ||
private String areaCode; | ||
|
||
@CsvBindByPosition(position = 1) | ||
private String description; | ||
|
||
@CsvBindByPosition(position = 2) | ||
private String existenceText; | ||
|
||
public String getAreaCode() { | ||
return areaCode; | ||
} | ||
|
||
public String getDescription() { | ||
return description; | ||
} | ||
|
||
public String getExistenceText() { | ||
return existenceText; | ||
} | ||
|
||
} | ||
|
||
public static class CsvData3 { | ||
|
||
@CsvBindByPosition(position = 0) | ||
private String area1; | ||
|
||
@CsvBindByPosition(position = 1) | ||
private String area2; | ||
|
||
@CsvBindByPosition(position = 2) | ||
private String area3; | ||
|
||
@CsvBindByPosition(position = 3) | ||
private String area4; | ||
|
||
@CsvBindByPosition(position = 4) | ||
private String area5; | ||
|
||
@CsvBindByPosition(position = 5) | ||
private String latitude; | ||
|
||
@CsvBindByPosition(position = 6) | ||
private String longitude; | ||
|
||
public String getArea1() { | ||
return area1; | ||
} | ||
|
||
public String getArea2() { | ||
return area2; | ||
} | ||
|
||
public String getArea3() { | ||
return area3; | ||
} | ||
|
||
public String getArea4() { | ||
return area4; | ||
} | ||
|
||
public String getArea5() { | ||
return area5; | ||
} | ||
|
||
public String getLatitude() { | ||
return latitude; | ||
} | ||
|
||
public String getLongitude() { | ||
return longitude; | ||
} | ||
|
||
} | ||
|
||
} | ||
135 changes: 135 additions & 0 deletions
135
src/test/java/com/catcher/core/LocationInsertTests.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
package com.catcher.core; | ||
|
||
import com.catcher.core.domain.entity.Location; | ||
import com.catcher.infrastructure.jpa.repository.LocationJpaRepository; | ||
import com.catcher.core.request.KakaoMapsRequest; | ||
import org.junit.jupiter.api.Disabled; | ||
import org.junit.jupiter.api.Test; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.test.context.SpringBootTest; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
import java.io.IOException; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
/* | ||
테스트 코드가 아닌 1회성 location 테이블 데이터 적재용 코드입니다. | ||
원본 데이터 파일이 필요할 경우 요청주세요 | ||
*/ | ||
|
||
@SpringBootTest | ||
public class LocationInsertTests { | ||
|
||
@Autowired | ||
LocationJpaRepository locationJpaRepository; | ||
|
||
@Autowired | ||
KakaoApiClient kakaoApiClient; | ||
|
||
@Test | ||
@Transactional | ||
@Disabled | ||
public void 지역코드_삽입() throws IOException { | ||
CsvReader csvReader = new CsvReader(); | ||
var list = csvReader.readCSVFile("${your_file_source}", '\t', "EUC-KR", CsvReader.MyCSVData.class); | ||
|
||
list.forEach(row -> { | ||
if (row.getExistenceText().equals("존재")) { | ||
locationJpaRepository.save(Location.initLocation(row.getAreaCode(), row.getDescription())); | ||
} | ||
}); | ||
} | ||
|
||
@Test | ||
@Transactional | ||
@Disabled | ||
public void 지역코드_좌표_매핑() throws IOException { | ||
CsvReader csvReader = new CsvReader(); | ||
var list = csvReader.readCSVFile("${your_file_source}", ',', "EUC-KR", CsvReader.CsvDataWithNumber.class); | ||
|
||
final AtomicInteger i = new AtomicInteger(0); | ||
list.forEach(row -> { | ||
|
||
if (row.getType().equals("B")) { | ||
var locationOptional = locationJpaRepository.findByAreaCode(row.getAreaCode()); | ||
if (locationOptional.isPresent()) { | ||
var location = locationOptional.get(); | ||
location.editCoordinates(row.getLatitude(), row.getLongitude()); | ||
locationJpaRepository.save(location); | ||
} | ||
} | ||
|
||
}); | ||
} | ||
|
||
@Test | ||
@Transactional | ||
@Disabled | ||
public void 지역코드_좌표_매핑2() throws IOException { | ||
CsvReader csvReader = new CsvReader(); | ||
var list = csvReader.readCSVFile("{your_file_source}", ',', "UTF-8", CsvReader.CsvData3.class); | ||
|
||
list.forEach(row -> { | ||
|
||
if (!row.getLatitude().isBlank() && !row.getLongitude().isBlank()) { | ||
var locationString = String.join(" ", row.getArea1(), row.getArea2(), row.getArea3(), row.getArea4(), row.getArea5()); | ||
var locationOptional = locationJpaRepository.findByDescription(locationString); | ||
if (locationOptional.isPresent()) { | ||
var location = locationOptional.get(); | ||
if (location.getLatitude() != null) { | ||
location.editCoordinates(row.getLatitude(), row.getLongitude()); | ||
locationJpaRepository.save(location); | ||
} | ||
} | ||
} | ||
|
||
}); | ||
} | ||
|
||
@Test | ||
@Transactional | ||
@Disabled | ||
public void 지역코드_좌표_매핑_with_kakao() throws IOException { | ||
|
||
var locationList = locationJpaRepository.findAll(); | ||
|
||
for (var location : locationList) { | ||
var response = kakaoApiClient.searchAddress(KakaoMapsRequest.createDefaultRequest(location.getDescription()), "${your_kakao_key}"); | ||
|
||
if (response.getDocuments().isEmpty()) { | ||
System.out.println("-----------------------------------"); | ||
continue; | ||
} | ||
if (location.getAreaCode().equals(response.getDocuments().get(0).getAddress().getAreaCode())) { | ||
location.editCoordinates(response.getDocuments().get(0).getAddress().getLatitude(), response.getDocuments().get(0).getAddress().getLongitude()); | ||
} else { | ||
System.out.println("-----------------------------------"); | ||
} | ||
} | ||
|
||
locationJpaRepository.saveAll(locationList); | ||
|
||
|
||
} | ||
|
||
@Test | ||
@Transactional | ||
@Disabled | ||
public void 지역코드_null_제거() { | ||
var locationList = locationJpaRepository.findAllByLatitudeIsNull(); | ||
|
||
for (var location : locationList) { | ||
if (!location.getAreaCode().endsWith("00")) { | ||
var newAreaCode = location.getAreaCode().substring(0, location.getAreaCode().length() - 2) + "00"; // 리 단위일 경우 면 단위 좌표로 대체 | ||
var newLocation = locationJpaRepository.findByAreaCode(newAreaCode).get(); | ||
location.editCoordinates(newLocation.getLatitude(), newLocation.getLongitude()); | ||
} | ||
} | ||
|
||
locationJpaRepository.saveAll(locationList); | ||
} | ||
|
||
|
||
} | ||
|
||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이 코드는 위치 데이터를 적재하는 테스트용 코드입니다. 리뷰와 개선 제안은 다음과 같습니다:
문제에 언급된 사항 외에도 추가적인 리뷰 사항은 다음과 같습니다:
이외에도 리뷰를 진행하기 위해서는 외부 종속성 및 CSV 파일의 정확한 구조 등에 대한 정보가 필요합니다. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
위의 코드 패치에 대해 간단한 코드 리뷰를 도와드리겠습니다.
이 코드는 CSV 파일을 읽어오는 기능을 제공하는 CsvReader 클래스와 이를 사용하기 위해 정의된 몇 가지 내부 클래스로 구성되어 있습니다.
주요 메소드인 readCSVFile은 filePath(파일 경로), separator(구분자), charset(문자셋), clazz(데이터 형식)를 매개변수로 받아 CSV 파일을 읽어 오는 기능을 수행합니다. try-with-resources 구문을 사용하여 파일과 관련된 리소스를 자동으로 닫습니다. CSVReaderBuilder를 사용하여 필요한 설정을 적용하고, CsvToBeanBuilder를 사용하여 CSV 데이터를 Java 객체로 변환하는 과정을 수행합니다. 마지막으로 변환된 객체 리스트를 반환합니다.
내부 클래스인 CsvDataWithNumber, MyCSVData, CsvData3는 각각 다른 형식의 CSV 데이터를 나타내는 클래스입니다. @CsvBindByPosition 어노테이션을 사용하여 CSV 열과 클래스 필드를 매핑합니다. 각 내부 클래스에는 getter 메소드가 정의되어 있습니다.
개선 사항:
패키지 이름을 보다 구체적으로 지정할 수 있습니다. com.catcher.core보다는 더 식별 가능한 패키지 이름을 선택하는 것이 좋습니다.
CsvReader 클래스는 일반적으로 유틸리티 클래스로 사용되므로, 생성자를 private으로 선언하여 인스턴스화할 수 없도록 하는 것이 좋습니다.
리소스 관리를 위해 InputStreamReader와 FileInputStream을 사용하고 있지만, Java 7 이후부터는 Files.newBufferedReader 메소드를 사용하여 간결하게 파일을 읽어올 수 있습니다. 공식적인 자원 관리 기능을 활용하여 코드를 더 단순화할 수 있습니다.
CsvReader 클래스의 일부 기능은 현재 클래스 밖에서도 사용될 수 있는 경우, 유틸리티 클래스로 분리시키는 것이 좋습니다.
예외 처리에 대한 문제가 없어 보입니다. 그러나 해당 메소드가 적절한 예외를 throws하고 있는지 확인하는 것이 좋습니다.
다른 개발자들이 코드를 읽고 이해하기 쉽도록 주석을 추가하는 것이 좋습니다. 코드 블록과 클래스에 대한 목적과 동작에 대한 설명을 추가하는 것이 도움이 됩니다.
이정도로 코드를 리뷰해보았습니다. 추가적인 정보나 질문이 있다면 언제든지 물어보세요!