You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
마이바티스 스프링 연동 모듈이 만들어주는 ItemMapper 구현체 덕분에 인터페이스 만으로 편리하게 XML의 데이터를 찾아서 호출할 수 있다.
매퍼 구현체 덕분에 번잡한 코드를 거치는 과정을 생략할 수 있다.
매퍼 구현체는 예외 변환까지 처리해준다. MyBatis에서 발생한 예외를 스프링 예외 추상화인 DataAccessException 에 맞게 변환해서 반환해준다.
▶️참고
마이바티스 스프링 연동 모듈이 자동으로 등록해주는 부분은 MybatisAutoConfiguration 클래스를 참고하자.
6️⃣ MyBatis 기능 정리1 - 동적 쿼리
✅ 동적 SQL
if
choose (when, otherwise)
trim(where, set)
foreach
if
<selectid="findActiveBlogWithTitleLike"resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<iftest="title != null">
AND title like #{title}
</if>
</select>
내부의 문법은 OGNL을 사용한다. 자세한 내용은 OGNL을 검색해보자.
choose, when, otherwise
<selectid="findActiveBlogLike"resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<whentest="title != null">
AND title like #{title}
</when>
<whentest="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
trim, where, set
<selectid="findActiveBlogLike"resultType="Blog">
SELECT * FROM BLOG
WHERE
<iftest="state != null">
state = #{state}
</if>
<iftest="title != null">
AND title like #{title}
</if>
<iftest="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
→ 위 예제에서 주의해야할 점
잘못된 예) where 뒤에 없을 때
SELECT*FROM BLOG
WHERE
잘못된 예) and가 먼저나와서 잘못되었을 때
SELECT*FROM BLOG
WHEREAND title like ‘someTitle’
사용
를 사용하면 where 문장에 조건을 만족하지 않으면 실행되지 않는다.
를 사용하면 and가 먼저 시작하는 조건이면 and를 삭제하고 실행된다.
<selectid="findActiveBlogLike"resultType="Blog">
SELECT * FROM BLOG
<where>
<iftest="state != null">
state = #{state}
</if>
<iftest="title != null">
AND title like #{title}
</if>
<iftest="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
- 컬랙션을 반복 처리할 때 사용
- 예) where in (1,2,3,4,5)와 같은 문장을 처리할 때
- 파라미터 List를 전달하면 된다.
<selectid="selectPostIn"resultType="domain.blog.Post">
SELECT *
FROM POST P
<where>
<foreachitem="item"index="index"collection="list"open="ID in ("separator=","close=")"nullable="true">
#{item}
</foreach>
</where>
</select>
7️⃣ MyBatis 기능 정리2 - 기타 기능
다음과 같이 XML 대신에 애노테이션에 SQL을 작성할 수 있다.
@Select("select id, item_name, price, quantity from item where id=#{id}")
Optional<Item> findById(Longid);
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
4️⃣ MyBatis 적용2 - 설정과 실행
ItemRepository를 구현해서MyBatisItemRepository를 만들자.MyBatisItemRepository는 단순히 ItemMapper 에 기능을 위임한다.
MyBatisConfig
MyBatisConfig는ItemMapper를 주입받고, 필요한 의존관계를 만든다.코드 추가 및 변경
테스트 실행해 보기
애플리케이션 실행
5️⃣ MyBatis 적용 3 - 분석
ItemMapper 매퍼 인터페이스의 구현체가 없는데 어떻게 동작하는 것일까?
ItemMapper 인터페이스
@Mapper가 붙어있는 인터페이스를 조사한다.ItemMapper인터페이스의 구현체를 만든다.✅ 매퍼 구현체
DataAccessException에 맞게 변환해서 반환해준다.6️⃣ MyBatis 기능 정리1 - 동적 쿼리
✅ 동적 SQL
if
choose (when, otherwise)
trim(where, set)
foreach
if
내부의 문법은 OGNL을 사용한다. 자세한 내용은 OGNL을 검색해보자.
choose, when, otherwise
→ 위 예제에서 주의해야할 점
7️⃣ MyBatis 기능 정리2 - 기타 기능
다음과 같이 XML 대신에 애노테이션에 SQL을 작성할 수 있다.
<select id="findById"> ~ </select>는 제거해야 한다.✅ 문자열 대체(String Substitution)
${}를 사용하면 된다.✅ 재사용 가능한 SQL 조각
✅ Result Maps
✅ 복잡한 결과 매핑
All reactions