-
데이터 접근 기술 - MyBatis카테고리 없음 2024. 2. 14. 20:55
#MyBatis mybatis.type-aliases-package=hello.itemservice.domain mybatis.configuration.map-underscore-to-camel-case=true logging.level.hello.itemservice.repository.mybatis=trace
MyBatis는 앞서 설명한 JdbcTemplate보다 더 많은 기능을 제공하는 SQL Mapper이다.
기본적으로 JdbcTemplate이 제공하는 대부분의 기능을 제공한다.
JdbcTemplate과 비교해서 MyBatis의 가장 매력적인 점은 SQL을 XML에 편리하게 작성할 수 있고,
또 동적 쿼리를 매우 편리하게 작성할 수 있다는 점이다.
JdbcTemplate SQL 여러줄 예시
String sql = "update item " + "set item_name=:itemName, price=:price, quantity=:quantity " + "where id=:id";
MyBatis SQL 여러줄 예시
<update id="update"> update item set item_name=#{itemName}, price=#{price}, quantity=#{quantity} where id = #{id} </update>
MyBatis는 XML에 작성하기 때문에 라인이 길어져도 문자 더하기에 대한 불편함이 없다.
JdbcTemplate - 동적 쿼리 예시
String sql = "select id, item_name, price, quantity from item"; //동적 쿼리 if (StringUtils.hasText(itemName) || maxPrice != null) { sql += " where"; } boolean andFlag = false; if (StringUtils.hasText(itemName)) { sql += " item_name like concat('%',:itemName,'%')"; andFlag = true; } if (maxPrice != null) { if (andFlag) { sql += " and"; } sql += " price <= :maxPrice"; } log.info("sql={}", sql); return template.query(sql, param, itemRowMapper());
MyBatis - 동적 쿼리 예시
<select id="findAll" resultType="Item"> select id, item_name, price, quantity from item <where> <if test="itemName != null and itemName != ''"> and item_name like concat('%',#{itemName},'%') </if> <if test="maxPrice != null"> and price <= #{maxPrice} </if> </where> </select>
JdbcTemplate은 자바 코드로 직접 동적 쿼리를 작성해야 한다.
반면에 MyBatis는 동적 쿼리를 매우 편리하게 작성할 수 있는 다양한 기능들을 제공해준다.
설정의 장단점
JdbcTemplate은 스프링에 내장된 기능이고, 별도의 설정없이 사용할 수 있다는 장점이 있다.
반면에 MyBatis는 약간의 설정이 필요하다.
정리
프로젝트에서 동적 쿼리와 복잡한 쿼리가 많다면 MyBatis를 사용하고, 단순한 쿼리들이 많으면 JdbcTemplate을 선택해서 사용하면 된다.
물론 둘을 함께 사용해도 된다, 하지만 MyBatis를 선택했다면 그것으로 충분할 것이다.
MyBatis - application.properties 설정
#MyBatis mybatis.type-aliases-package=hello.itemservice.domain mybatis.configuration.map-underscore-to-camel-case=true logging.level.hello.itemservice.repository.mybatis=trace
mybatis.type-aliases-package
- 마이바티스에서 타입 정보를 사용할 때는 패키지 이름을 적어주어야 하는데, 여기에 명시하면 패키지 이름을 생략할 수 있다.
- 지정한 패키지와 그 하위 패키지가 자동으로 인식된다.
- 여러 위치를 지정하면 ',', ';'로 구분하면 된다
mybatis.configuration.map-underscore-to-camel-case
- JdbcTemplate의 BeanPropertyRowMapper에서 처럼 언더바를 카멜로 자동으로 변경해주는 기능을 활성화 한다.
바로 다음에 설명하는 관례의 불일치 내용을 참고하자.
logging.level.hello.itemservice.repository.mybatis=trace
- MyBatis에서 실행되는 쿼리 로그를 확인할 수 있다.
관례의 불일치
자바 객체에는 주로 카멜(camelCase)표기법을 사용하고, itemName 처럼 중간에 낙타 봉이 올라와 있는 표기법이다
반면에 관꼐형 데이터베이스에서는 주로 언더스코어를 사용하는 snake_case 표기법을 사용한다.
item_name처럼 중간에 언더스코어를 사용하는 표기법이다.
이렇게 관례로 많이 사용하다 보니 map-underscore-to-camel-case 기능을 활성화 하면 언더스코어 표기법을 카멜로 자동 변환해준다. 따라서 DB에서 select item_name으로 조회해도 객체의 itemName(setItemName()) 속성에 값이 정상 입력된다.
정리하면 해당 옵션을 켜면 스네이크표기법은 자동으로 해결되서 그냥 두면 되고, 컬럼 이름과 객체 이름이 완전히 다르면 조회 SQL에서 별칭을 사용하면 된다.