Repository와 Service에 문자열을 포함하는 List를 반환하는 JPA를 추가 했다.
List<StockInfo> findByItmsNmContaining(String keyword);
List<StockInfo> findBySrtnCdContaining(String keyword);
Containing을 통해 keyword를 포함하는 문자열을 받아온다.
public List<String> findAllByQuery(String query) {
List<StockInfo> stockInfos;
if(query.charAt(0) <= '9' && query.charAt(0) >= '0') {
stockInfos = stockInfoRepository.findBySrtnCdContaining(query);
}else{
stockInfos = stockInfoRepository.findByItmsNmContaining(query);
}
List<String> result = new ArrayList<>();
for(StockInfo stockInfo : stockInfos) {
result.add(stockInfo.getItmsNm() +" (" + stockInfo.getSrtnCd() + ")");
}
return result;
}
문자열의 첫 번째 문자를 기준으로 종목명, 종목코드로 검색을 하고 문자열로 변환하여 "종목명 (종목코드)"의 List를 반환하였다.
모달에서 데이터 통신을 위해 Controller를 만들었다.
@Controller
public class SearchController {
private final StockInfoService stockInfoService;
public SearchController(StockInfoService stockInfoService) {
this.stockInfoService = stockInfoService;
}
@GetMapping("/searchStock")
public ResponseEntity<List<String>> searchStock(@RequestParam String searchTerm) {
List<String> searchResult = stockInfoService.findAllByQuery(searchTerm);
return ResponseEntity.ok(searchResult);
}
}
다음과 같이 구성하였고 클릭시 해당 종목을 선택하고 모달창이 닫힌다.
for(int i = 1 ; i <= Integer.parseInt(params.get("count")) ; i++){
String stockName = params.get("stock" + i);
int indexOfParenthesis = stockName.indexOf('(');
stockNames.add(stockName.substring(0, indexOfParenthesis - 1).trim());
weights.add(Double.parseDouble(params.get("weight" + i)));
}
다음과 같이 종목명만 가져오도록 변경하였다.