데이터 접근 기술 - MyBatis

2025. 10. 21. 00:41·Spring

MyBatis는 JdbcTemplate보다 더 많은 기능을 제공하는 SQL Mapper이다.

기본적으로 JdbcTemplate이 제공하는 대부분의 기능을 제공한다.

SQL을 XML에 편리하게 작성할 수 있고 또 동적 쿼리를 매우 편리하게 작성할 수 있다는 장점이 있다.

 

ItemMapper 인터페이스

package hello.itemservice.repository.mybatis;

import hello.itemservice.domain.Item;
import hello.itemservice.repository.ItemSearchCond;
import hello.itemservice.repository.ItemUpdateDto;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Optional;

@Mapper
public interface ItemMapper {

    void save(Item item);

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

    List<Item> findAll(ItemSearchCond itemSearch);

    Optional<Item> findById(Long id);
}

 

- 마이바티스 매핑 xml을 호출해주는 Mapper Interface

- @Mapper 어노테이션을 붙여줘야 마이바티스에서 인식 가능

- 메서드를 호출하면 아래 xml의 해당 sql을 실행하고 결과 리턴

 

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>
</mapper>

 

insert - save

- Insert SQL은 <insert> 사용

- id에 인터페이스에서 설정한 메서드 이름을 지정하면 된다.

- 파라미터는 #{} 문법으로 사용한다. 매퍼에서 넘긴 객체의 프로퍼티 이름을 적어주면 된다.

- #{}는 PreparedStatement를 사용한다. ?를 치환한다고 생각하면 된다.

- userGeneratedKeys는 데이터베이스가 키를 생성해주는 IDENTITY 전략일 때 사용한다. keyProperty는 생성되는 키의 속성 이름을 지정한다. insert가 끝나면 item 객체의 id속성에 값이 입력된다.

 

update - update

- update SQL은 <update> tkdyd

- 파라미터가 2개 이상일 때 @Param으로 이름을 지정해서 파라미터를 구분해야 한다. 1개일 땐 생략 가능

 

select - findById

- select SQL은 <select> 사용

- resultType은 반환 타입을 명시하면 된다. (BeanPropertyRowMapper처럼 SELECT SQL의 결과를 편리하게 객체로 변환해준다)

- 설정에서 언더스코어 표기법을 카멜 표기법으로 설정하는 방법이 있다.

- 자바 코드에서 반환 객체가 하나이면 Item, Optional<Item>과 같이 사용하면 되고, 하나 이상이면 컬렉션을 사용하면 된다.(주로 List)

 

select - findAll

- <where>, <if>같은 동적 쿼리 문법을 통해 편리한 동적 쿼리를 지원한다.

- <if>는 해당 조건이 만족하면 구문을 추가

- <if>가 모두 실패하면 SQL where를 만들지 않는다. 하나라도 성공한다면 처음 나타나는 and를 where로 변환해준다.

 

MyBatis 적용2 - 설정과 실행

MyBatisItemRepository

package hello.itemservice.repository.mybatis;

import hello.itemservice.domain.Item;
import hello.itemservice.repository.ItemRepository;
import hello.itemservice.repository.ItemSearchCond;
import hello.itemservice.repository.ItemUpdateDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
@RequiredArgsConstructor
public class MyBatisItemRepository implements ItemRepository {

    private final ItemMapper itemMapper;

    @Override

    public Item save(Item item) {
        itemMapper.save(item);
        return item;
    }

    @Override
    public void update(Long itemId, ItemUpdateDto updateParam) {
        itemMapper.update(itemId, updateParam);
    }

    @Override
    public Optional<Item> findById(Long id) {
        return itemMapper.findById(id);
    }

    @Override
    public List<Item> findAll(ItemSearchCond cond) {
        return itemMapper.findAll(cond);
    }
}

 

MyBatisConfig

package hello.itemservice.config;

import hello.itemservice.repository.ItemRepository;
import hello.itemservice.repository.jdbctemplate.JdbcTemplateItemRepositoryV3;
import hello.itemservice.repository.mybatis.ItemMapper;
import hello.itemservice.repository.mybatis.MyBatisItemRepository;
import hello.itemservice.service.ItemService;
import hello.itemservice.service.ItemServiceV1;
import lombok.RequiredArgsConstructor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@RequiredArgsConstructor
public class MyBatisConfig {

    private final ItemMapper itemMapper;

    @Bean
    public ItemService itemService() {
        return new ItemServiceV1(itemRepository());
    }

    @Bean
    public ItemRepository itemRepository() {
        return new MyBatisItemRepository(itemMapper);
    }
}

 

MyBatis 적용3 - 분석

ItemMapper의 구현체가 없는데 어떻게 동작했을까?

 

AOP 프록시를 떠올려보면 이해하기 쉽다.

 

1. 애플리케이션 로딩 시점에서 MyBatis 스프링 연동 모듈은 @Mapper가 있는 인터페이스를 찾는다.

2. 해당 인터페이스가 발견되면 동적 프록시 기술을 사용해서 ItemMapper 구현체를 만든다.

3. 생성된 구현체를 스프링 빈으로 등록한다.

 

매퍼 구현체는 xml의 데이터를 찾아서 호출하는 로직들을 수행한다.

당연히 예외 변환 기능도 제공한다.

 

자세한 문법은 따로 공부할 것

'Spring' 카테고리의 다른 글

스프링 트랜잭션 전파1  (0) 2025.11.02
스프링 트랜잭션 이해  (0) 2025.10.30
데이터 접근 기술 - 테스트  (0) 2025.10.20
데이터 접근 기술 - 스프링 JdbcTemplate  (0) 2025.10.18
스프링과 문제 해결 - 예외처리, 반복  (0) 2025.10.17
'Spring' 카테고리의 다른 글
  • 스프링 트랜잭션 전파1
  • 스프링 트랜잭션 이해
  • 데이터 접근 기술 - 테스트
  • 데이터 접근 기술 - 스프링 JdbcTemplate
공부처음하는사람
공부처음하는사람
  • 공부처음하는사람
    lazzzykim
    공부처음하는사람
  • 전체
    오늘
    어제
    • 분류 전체보기 (159)
      • Kotlin (31)
      • Java (56)
      • Spring (44)
      • JPA (6)
      • Algorithm (3)
      • TroubleShooting (1)
      • 내일배움캠프 프로젝트 (14)
      • Setting (2)
      • ... (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
  • 링크

  • 인기 글

  • 태그

    내일배움캠프
    제네릭
    빈 생명주기
    예외처리
    jpa
    김영한
    트랜잭션
    김영한의 실전자바
    kotlin
    중첩클래스
    OCP
    배열
    싱글톤
    캡슐화
    java
    다형성
    spring
    김영한의 실전 자바
    Di
    언체크예외
  • hELLO· Designed By정상우.v4.10.3
공부처음하는사람
데이터 접근 기술 - MyBatis
상단으로

티스토리툴바