[Java Spring] 마이바티스(MyBatis)란?

khj·2025년 4월 7일

Java

목록 보기
6/11
post-thumbnail

Spring 기반의 백엔드 개발에서 데이터를 다룰 때 가장 널리 사용되는 ORM 기술은 JPA다.
그러나 복잡한 SQL을 직접 작성하고 싶거나, 쿼리 튜닝이 중요한 프로젝트에서는 MyBatis가 강력한 대안이 된다.

1. 마이바티스(MyBatis)란?

MyBatis는 SQL을 XML 또는 애너테이션으로 분리해 작성할 수 있게 도와주는 SQL 매퍼 프레임워크다.
직접 SQL을 작성하되, 자바 객체와 자동으로 매핑해주는 기능을 제공한다.


즉, JDBC의 반복적인 코드들을 줄이면서도, SQL은 직접 제어하고 싶은 경우에 유용하다.


2. 마이바티스를 왜 사용할까?

기능 설명
직접 SQL 작성 복잡한 쿼리를 직접 컨트롤 가능
자동 매핑 쿼리 결과를 자바 객체로 자동 변환
XML 또는 애너테이션 지원 SQL을 외부 XML로 분리할 수 있음
유연한 조인 처리 다중 테이블 조인 결과를 POJO로 쉽게 매핑
학습 곡선이 낮음 단순한 구조로 빠르게 학습 가능

3. MyBatis 기본 구조

MyBatis를 사용할 때 구성은 보통 다음과 같다.

  • 매퍼 인터페이스 (Mapper Interface)
  • 매퍼 XML 파일 (Mapper XML)
  • SQL 세션 및 설정 (MyBatis Config)
  • 도메인 객체 (DTO, Entity 등)

✅ 예제: 회원 정보를 조회하는 Mapper

📁 1. Member.java (DTO)

public class Member {
    private Long id;
    private String username;
    private String email;
    // getter, setter 생략
}

📁 2. MemberMapper.java (인터페이스)

@Mapper
public interface MemberMapper {
    Member findById(Long id);
}

📁 3. MemberMapper.xml (SQL 매핑)

<?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="com.example.mapper.MemberMapper">

    <select id="findById" parameterType="long" resultType="com.example.dto.Member">
        SELECT id, username, email
        FROM member
        WHERE id = #{id}
    </select>

</mapper>

4. Spring Boot에 MyBatis 적용 방법

4.1. 의존성 추가 (build.gradle)

dependencies {
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2'
}

4.2. 설정 (application.yml)

mybatis:
  mapper-locations: classpath:mapper/**/*.xml
  type-aliases-package: com.example.dto

4.3. Mapper 스캔

@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

5. MyBatis vs JPA 비교

항목 MyBatis JPA
SQL 제어 완전 수동 대부분 자동
성능 튜닝 유리 상대적으로 제한
학습 난이도 낮음 비교적 높음
코드 생산성 낮음 높음
자유도 매우 높음 낮음 (추상화됨)
profile
Spring, Django 개발 블로그

0개의 댓글