본문 바로가기
DataBase/MyBatis

[Mybatis] @Annotation vs XML, 파라미터 다루기

by 정고정 2021. 10. 31.
반응형

@Annotation vs XML

MyBatis 공식적으로는 어노테이션보다 XML을 권장하고 있다. 

3.xx 버전이 나오면서 어노테이션 방식도 지원은 하지만 애초에 어노테이션은 XML설정의 일부분만 사용할 뿐이라 좀 복Nested Join Mapping 같은 경우에는 XML을 쓰는 게 훨씬 낫다고 한다. 

 

물론 어노테이션 쓰면 JPA에서 네이티브 쿼리 쓰는 느낌이고 깔끔한데다 직관적이긴 하다.  

그런데 확실히 mybatis에서 어노테이션으로 쓰라고 제공해주는 기능만 쓸 수 있는 감이 있음. 

동적쿼리의 경우 어노테이션에서는 script달아서 써야 하는 것 같은데 그렇게까지 쓸 바에는 xml파일을 따로 만들어 쓰는 게 훨씬 나아 보인다. 

 

동적쿼리를 써야 하는 메소드가 있는 경우 둘을 혼용해서 쓸까 고민 좀 해 봤는데 이 경우도 XML로 통일하는 게 나은 것 같다.

하지만 확장 예정이 없고 + 검색필터나 정렬이 없고 + 가변 필드도 두 개인 공지용 DB는 어노테이션으로만 쓰는 게 편할 것 같았다.

 

 

파라미터 이용해서 쿼리 짜기 

@Mapper
public interface NoticeRepository {
	
	@Options(useGeneratedKeys = true, keyProperty = "notice_id")			
	@Insert("INSERT INTO notice (`notice_title`, `notice_content`, `created`) VALUES (#{notice_title}, #{notice_content}, sysdate())")
	Long saveNotice(NoticeSaveRequestDto requestDto);
	
	@Select("select * from notice")
	List<Notice> findAll();
	
	@Select("select * from notice where notice_id=#{notice_id}")	
	Notice findNoticeByNoticeId(Long notice_id);
	
	@Delete("delete from notice where notice_id=#{notice_id}")
	Long deleteNotice(Long notice_id);
	
	@Update("update notice set notice_title=#{requestDto.notice_title}, notice_content=#{requestDto.notice_content} where notice_id=#{notice_id}")
	Long updateNotice(Long notice_id, NoticeUpdateRequestDto requestDto);
}

 

마지막 updateNotice()의 경우 Long타입의 notice_id와 NoticeUpdateRequestDto requestDto를 받는다. 

그런데 requestDto도 Long notice_id를 가지고 있다. 이 경우에 쿼리에는 어떤 notice_id가 들어갈까?

 

정답은 파라미터에 있는 notice_id다. requestDto 안에 있는 notice_id는 requestDto.notice_id로 접근해야 한다.

같은 맥락에서, requestDto 안에 있는 변수를 떼 오려면 requestDto.notice_title처럼 접근해 줘야 한다. 혹시 updateNotice()에서는 이름이 중복되는 변수가 두 개라 따로 표시해줘야 하는 건가 해서 해당 함수에서 쓰는 requesDto에서 id 컬럼을 지워봤는데 안 돌아간다. 파라미터가 두 개면 무조건 변수 출처를 명시해 줘야 하나 보다.  

근데 파라미터가 하나뿐인 첫번째 saveNotice()의 경우 requstDto 객체가 소유한 변수라고 명시해주지 않아도 변수를 제대로 인식해서 매핑되는 것을 볼 수 있다.

 

결론

파라미터가 하나만 들어오면 알아서 잘 매핑하지만 파라미터가 둘 이상일 경우 꼭 변수 출처를 표시해 줘야 한다. 

 

 

반응형

'DataBase > MyBatis' 카테고리의 다른 글

[Spring/Mybatis] auto increment id값 return하기  (0) 2021.10.30

댓글