[JAVA, Angular] 자바

실습과 예제 코드는 JAVA, Angular(13.3.3), TypeScript(4.4.4) 및 mariaDB(MySQL) 환경에서 생성되었습니다.

검색창에서 검색할 경우 스페이스바(공백)로 구분하여 단어를 검색하고, -를 추가하여 검색하면 해당 단어가 검색되지 않습니다.

검색 기능을 만들고 싶었습니다.

먼저 기본적으로 프론트 태스크로 사용되는 검색에 사용할 변수를 선언합니다.

API에 연결하여 검색 로직을 실행합니다.

// 검색 시 실행!
retrieve() {
// srchString : 단어 검색용 변수
  this.rest.srchWord(this.srchString).subscribe(
      result => {
        this.srchRslt = result;
      }
  );
}

백엔드 작업으로 srchString 변수에 포함된 정보를 수신하고 서버에서 처리할 API를 생성해야 합니다.

제어 장치

@PostMapping(value = "/srchView")
public ResponseEntity<List<srchRslt>> postSrchPrdct(@RequestBody String srch) {
    SrchCond cond = new SrchCond();
    cond.setSrch(srch);
    return new ResponseEntity<>(srchPrdctService.retrieveSrch(cond), HttpStatus.OK);
}

입력된 srchString을 srch에 넣고 서비스에서 정보를 제어하고 마지막으로 쿼리를 실행하여 원하는 결과를 도출합니다.

정보 포함 조건은 단어별 검색에서 포함 조건으로 사용되는 변수와 제외 조건으로 사용되는 변수를 포함하는 정보를 포함한다.

상태

public class SrchCond {

    @ApiModelProperty(position = 1, value = "검색내용", example = "가나다라마바사")
    private String srch;

    // 제품명 검색 조건 확장 변수
    private List<String> srchList = new ArrayList<>();

    // 제품명 검색 조건 확장 변수('-'입력 단어 처리)
    private List<String> srchNonList = new ArrayList<>();
}

서비스

List<SrchRslt> retrieveSrch(SrchCond cond) {
    // 입력받은 단어 길이 체크
    if(!checkString(cond.getSrch())) {
        // 스페이스바로 단어 분리
        String() srchTemp = cond.getSrch().split(" ");
        // 검색어에 포함시킬 단어리스트
        List<String> SrchLikeList = new ArrayList<>();
        // 검색어에 제외시킬 단어리스트 ex) -단어 -> 해당단어 제외
        List<String> SrchNonLikeList = new ArrayList<>();

        // 입력된 단어들을 공백(스페이스바)로 구분지어 배열에 저장하는 작업
        for (String item : srchTemp) {
            // 길이가 0보다 큰 단어만을 검색하며 단어의 첫 글자가 - 인지 판별한다
            // ( 첫 글자가 - 이면 검색어에 포함되지 않는 배열에 저장, 그렇지 않으면 포함되는 배열에 저장)
            if (item.length() > 0) {
                if (item.charAt(0) == '-') {
                    // 제외 할 대상의 단어에는 -가 포함되어있으므로 -를 제외하고 저장한다
                    SrchNonLikeList.add(item.replace("-",""));
                } else {
                    SrchLikeList.add(item);
                }
            }
        }
        // 검색할 단어와 제외할 단어 리스트를 저장한다
        cond.setSrchList(SrchLikeList);
        cond.setSrchNonList(SrchNonLikeList);
    }
    return this.srchMapper.retrieveSrch(cond);
}

입력된 검색어(단어)는 – 여부와 상관없이 제외할 단어와 검색할 단어 목록에 저장됩니다.

cond에 리스트를 포함시켜 최종적으로 단어를 분류하는 논리입니다.

매퍼

List<SrchRslt> retrieveSrch(SrchCond cond);

XML

<select id="retrieveSrch" parameterType="경로.SrchCond" resultType="경로.SrchRslt">
    SELECT
	검색할 목록
    .
    .
    중략
    .
    .
    FROM 테이블
    .
    .
    <where>
        <if test="srchList.size != 0 or srchNonList.size != 0">
            <foreach item="item" index="index" collection="srchList">
                AND 검색대상 LIKE CONCAT('%',#{item},'%')
            </foreach>
        </if>
        <if test="srchNonList.size != 0">
            <foreach item="item" index="index" collection="srchNonList">
                AND 검색대상 NOT LIKE CONCAT('%',#{item},'%')
            </foreach>
        </if>
    </where>
</select>

select , from , join 등 적절한 정보를 입력한 후 where 절에 입력된 단어를 서비스에서 처리

검색할 단어 목록과 제외할 단어 목록을 구성하고 검색 조건을 생성합니다.

목록이 존재하지 않는 한 실행되며 유사한 검색에 대한 결과를 반환합니다.


일반 검색에서


일반 검색 + 스페이스바 + 일반 검색


일반 검색 + 공백 + 제외 검색