🍃Spring

[Spring DB] MyBatis 사용하기

waveofmymind 2023. 1. 29. 13:07

MyBatis란?

JdbcTemplate보다 많은 기능을 제공하는 SQL Mapper

SQL을 XML에 편하게 작성할 수 있고, 동적 쿼리를 편리하게 작성할 수 있다.

 

SQL이 여러 줄인 경우 비교

//JdbcTemplate
String sql = "update item " +
 "set item_name=:itemName, price=:price, quantity=:quantity " +
 "where id=:id";
 
 //MyBatis
 <update id="update">
 update item
 set item_name=#{itemName},
 price=#{price},
 quantity=#{quantity}
 where id = #{id}
</update>
  • JdbcTemplate과 같은 경우 SQL이 여러 줄인 경우, 공백으로 인한 오류가 발생할 수 있다.
  • MyBatis의 경우 SQL이 여러줄이여도 XML로 작성하기 때문에 편리하다.

동적 쿼리의 경우, JdbcTemplate은 자바 코드로 직접 동적 쿼리를 작성해야 하지만, MyBatis는 if 태그 등으로 더 편리하게 작성할 수 있다.

 

  • 동적 쿼리와 복잡한 쿼리가 많을 경우 -> MyBatis
  • 단순한 쿼리들이 많을 경우 -> JdbcTemplate

기본

다음과 같이 인터페이스를 작성한다.

@Mapper
public interface ItemMapper {

    void save(Item item);

    void update(@Param("id") Long id, @Param("updateParam")ItemUpdateDto updateDto);

    Optional<Item> findById(Long id);

    List<Item> findAll(ItemSearchCond itemSearch);
}

그리고 resources 폴더 내에, 위 ItemMapper와 동일한 폴더 경로를 만들어서 ItemMapper.xml을 만든다.

그리고 태그를 이용해서 작성하면,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="hello.itemservice.repository.mybatis.ItemMapper">
    <insert id="save" useGeneratedKeys="true" keyProperty="id">
        insert into item (item_name,price,quantity)
        values (#{itemName},#{price},#{quantity})
    </insert>

    <update id="update">
        update item
        set item_name=#{updateParam.itemName},
            price=#{updateParam.price},
            quantity=#{updateParam.quantity}
        where id = #{id}
    </update>

    <select id="findById" resultType="Item">
        select id,item_name,price,quantity
        from item
        where id = #{id}
    </select>

    <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 $lt;= #{maxPrice}
            </if>
        </where>
    </select>

위와 같이 작성할 수 있다.

특히 findAll의 동적 쿼리 부분이 JdbcTemplate에 비해 단순해졌다는 것을 알 수 있다.

 

기능 정리

동적 SQL

마이바티스에서 제공하는 최고의 기능이다. 

  • If: 조건에 따라 추가할지 말지를 정할수 있다.
  • choose (when, otherwise): 자바의 switch 구문과 유사하다.
  • tim,where,set:  
  • foreach: 컬렉션을 반복처리할때 사용한다.

애노테이션으로 SQL 작성

XML 대신, 애노테이션으로 SQL을 작성할 수 있다.

@Select("select id,item_name,price,quantity from item where id=#{id}")
Optional<Item> findById(Long id);
  • @Insert,@Update,@Delete,@Select 기능이 제공된다.
  • 이 경우 XML 내의 해당 SQL문은 제거할 것
  • 동적 SQL이 해결되지 않으므로 권장 X

 

출처

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-2

 

스프링 DB 2편 - 데이터 접근 활용 기술 - 인프런 | 강의

백엔드 개발에 필요한 DB 데이터 접근 기술을 활용하고, 완성할 수 있습니다. 스프링 DB 접근 기술의 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., - 강의 소개 | 인

www.inflearn.com