날짜(yyyy/MM/dd) | 제목(링크달기) | 구현 | 정리 | 메모 |
---|---|---|---|---|
2024.05.31 | 노트 검색 1.1 |
이전 문제점
- NoteMapper.xml 의 sql 문으로 인해 title 과 content 둘 다 검색해야만 오류가 생기지 않는다.(하나라도 null 일 경우 문제)
- 둘 다 null 값인 경우의 처리
- 검색 조건이 늘어났을때의 수정의 어려움
위의 두가지가 저번에 발견한 문제점이다.
mybatis sql 수정
우선 sql 문을 수정하여 제목 '또는' 내용을 검색할시 검색이 가능하도록 수정하도록 해본다.
현재의 mapper.xml 의 sql문
<select id="selectSearchList" resultType="org.leeinwon.studylink.domain.NoteVO">
select * from notes
where (title like concat('%', #{title}, '%')
and content like concat('%', #{content}, '%'))
order by id asc
</select>
title 이나 content 의 내용이 있거나 없거나 조건에 따라 달라져야 하기 떄문에 Mybatis 의 동적 sql 문서를 참고 해봤다.
https://mybatis.org/mybatis-3/dynamic-sql.html
위 링크의 <where>
와 <if>
를 혼합하여 사용하기로 하였다
<select id="selectSearchList" resultType="org.leeinwon.studylink.domain.NoteVO">
select * from notes
<where>
<if test="title != null">
title like concat('%', #{title}, '%')
</if>
<if test="content != null">
and content like concat('%', #{content}, '%')
</if>
</where>
order by id asc
</select>
테스트
그 후 NoteMapperTest 클래스로 매퍼 테스트를 진행하였다(title 값과 content 값을 바꿔가며 확인)
DB 에는 아래 4개의 데이터를 생성했다.
id | title | content | createdate | updatedate |
---|---|---|---|---|
1597 | spring | 1 | 2024-05-31 21:55:57 | NULL |
1598 | spring | 1 | 2024-05-31 21:55:59 | NULL |
1599 | spring | 2 | 2024-05-31 21:56:01 | NULL |
1600 | java | 1 | 2024-05-31 21:56:33 | NULL |
@Log4j2
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/root-context.xml")
public class NoteMapperTests {
@Autowired(required = false)
private NoteMapper noteMapper;
. . .
@Test
public void testSelectSearchList(){
SearchDTO searchDTO = SearchDTO.builder()
.title("java")
.content("1")
.build();
List noteVOList = noteMapper.selectSearchList(searchDTO);
noteVOList.forEach(vo -> log.info(vo));
}
}
현재 노트검색 1.1 의 문제점
1. 검색 조건이 늘어날수록<if test="">
가 늘어나야 함을 뒤늦게 깨달았다....
검색 타입을 지정하는 SearchDTO 클래스에
public class SearchDTO{
private String title; private String content;
}
검색 타입 하나하나가 지정되어 있기 때문이다.
mybatis 문서(https://mybatis.org/mybatis-3/dynamic-sql.html) 를 볼때<foreach>
구문이 있었는데 Collection 에 대한 반복처리를 지원하는 구문이라고 한다.
당장 드는 생각에는 검색 조건을 Collection 타입으로 받아 각 원소를 mybatis 의 <if test="">
로 비교하여 sql 구문을 적용하면 될것 같다.
'포트폴리오 개발일지' 카테고리의 다른 글
2024-06-07 노트검색 1.3 오류해결 (0) | 2024.06.09 |
---|---|
2024-06-04 게시판검색 1.3 및 오류발생 (2) | 2024.06.08 |
개발일지 쓰는것도 만만치 않다.. (0) | 2024.06.07 |
2024.06.03 게시판 검색 1.2 (2) | 2024.06.03 |
2024-05-30 게시판 검색기능 구현 시작 1.0 (0) | 2024.06.01 |