
| 특징 | 설명 |
|---|---|
| SQL 직접 작성 | JPA는 SQL을 자동 생성하지만, MyBatis는 개발자가 직접 SQL을 작성함 |
| 유연한 제어 | 복잡한 쿼리 작성, 조건 분기, SQL 튜닝 등에 유리 |
| XML 또는 Annotation 방식 지원 | SQL을 XML 파일 또는 Java 어노테이션으로 관리 가능 |
| 자동 매핑 | 쿼리 결과를 Java 객체로 자동 매핑 (DTO, VO 등) |
| 비표준 ORM | 완전한 ORM은 아님 (객체 간 관계 자동 매핑은 안 함) |
public interface UserMapper {
User findById(Long id);
}
<mapper namespace="com.example.mapper.UserMapper">
<select id="findById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
User user = userMapper.findById(1L);
| 항목 | MyBatis | JPA |
|---|---|---|
| SQL 작성 | 직접 작성 | 자동 생성 (JPQL/Hibernate) |
| 제어력 | 높음 | 낮음 (자동화 중심) |
| 생산성 | 낮음 (SQL 수작업) | 높음 (자동화 많음) |
| 학습 곡선 | 낮음 | 비교적 높음 |
| 대규모 프로젝트 | 복잡한 쿼리나 성능 튜닝이 필요한 경우 적합 | 도메인 중심 설계(DDD)에 적합 |
복잡한 SQL을 직접 제어하고 싶을 때
데이터 중심의 시스템에서 성능 튜닝이 중요할 때
기존 레거시 시스템이 SQL 기반일 때
JPA의 N+1 문제 등 자동화가 부담될 때
// MyBatis Starter
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.3.1'
// MySQL JDBC 드라이버
runtimeOnly 'com.mysql:mysql-connector-j:8.0.33'
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb?serverTimezone=Asia/Seoul
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: com.example.domain
configuration:
map-underscore-to-camel-case: true