마이바티스 3 | 소개 – mybatis
마이바티스는 무엇인가? 마이바티스는 개발자가 지정한 SQL, 저장프로시저 그리고 몇가지 고급 매핑을 지원하는 퍼시스턴스 프레임워크이다. 마이바티스는 JDBC로 처리하는 상당부분의 코드와
mybatis.org
마이바티스 3 | 매퍼 XML 파일 – mybatis
Mapper XML 파일 마이바티스의 가장 큰 장점은 매핑구문이다. 이건 간혹 마법을 부리는 것처럼 보일 수 있다. SQL Map XML 파일은 상대적으로 간단하다. 더군다나 동일한 기능의 JDBC 코드와 비교하면
mybatis.org
https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start
Quick Start
MyBatis integration with Spring Boot. Contribute to mybatis/spring-boot-starter development by creating an account on GitHub.
github.com
MyBatis는 자바 애플리케이션에서 관계형 데이터베이스와의 상호작용을 단순화하는 SQL 매핑 프레임워크이다.
SQL 코드와 분리해 XML or Annotation으로 관리하며, JDBC API의 복잡함을 줄이고, SQL 중심의 데이터베이스 작업을 간소화함. ORM 도구인 Hibernate와 달리 SQL 제어권을 개발자에게 주고, 필요한 경우 직접 SQL을 작성할 수 있음
1. MyBatis의 주요 특징
1.1 SQL 중심의 데이터 접근
- SQL 제어권을 개발자에게 부여하여 고성능, 복잡한 쿼리를 쉽게 관리할 수 있음.
- SQL을 XML or Annotation으로 정의하여 재사용성과 유지보수성을 높임
1.2 간단한 매핑
- 데이터베이스 결과를 Java 객체로 매핑하기 위한 기능을 제공함
- ResultSet을 수동으로 처리하지 않아도 객체와 데이터베이스 필드를 쉽게 매핑할 수 있다.
1.3 동적 SQL 지원
- XML에서 <if>, <choose>, <foreach> 등을 사용하여 조건부 쿼리, 반복, 동적 쿼리를 작성할 수 있다.
1.4 플러그인 확장성
- MyBatis는 Interceptor를 통해 실행 시 동작을 확장할 수 있는 기능을 제공.
2. MyBatis의 주요 구성 요소
2.1 SqlSessionFactory
- 데이터베이스와의 세션을 생성하는 역할
- SqlSessionFactoryBuilder를 통해 생성되고, 설정 파일(mybatis-config.xml)을 기반으로 구성됨.
2.2 SqlSession
- MyBatis의 핵심 객체로, SQL 실행, 트랜잭션 관리, 매핑 작업 등을 처리함.
- 주요 메서드 :
- selectOne() , selectList(): 데이터 조회
- insert(), update(), delete() : 데이터 수정 및 삭제
2.3 Mapper
- SQL과 Java 인터페이스 간 매핑을 정의함
- XML 기반 또는 애너테이션 기반으로 작성할 수 있음.
3. MyBatis 설정 및 사용
3.1 Gradle 의존성 추가
dependencies {
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2'
implementation 'org.mariadb.jdbc:mariadb-java-client:3.1.2'
}
3.2 MyBatis 설정 파일 (mybatis-config.xml)
MyBatis의 글로벌 설정을 정의하는 파일
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"<https://mybatis.org/dtd/mybatis-3-config.dtd>">
<configuration>
<!-- 환경 설정 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
- mapUnderscoreToCamelCase : 데이터베이스의 snake_case 칼럼 이름을 Java의 camelCase 필드 이름으로 자동 매핑.
3.3 데이터베이스 설정
application.properties에서 데이터베이스 연결 정보를 설정한다.
spring.application.name=mybatisEx01
# Mariadb 설정
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/test2
spring.datasource.username=root
spring.datasource.password=!123456
# MyBatis 매퍼 설정
mybatis.mapper-locations=mappers/*.xml
mybatis.type-aliases-package=com.example.mybatis.dto
3.4 테이블과 매핑할 모델 클래스
package com.example.mybatis.dto;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class UserTO {
private int id;
private String name;
private String email;
}
3.5 매퍼 인터페이스
package com.example.mybatis.mapper;
import com.example.mybatis.dto.UserTO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from users")
List<UserTO> findAllUsers();
@Select("select * from users where id = #{id}")
UserTO findUserById(int id);
}
3.6 XML 매퍼
XML 파일에서 SQL을 정의할 수도 있음(위 Mapper Interface와 함께 사용 가능)
mapper/UserMapper.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="com.example.mybatis.mapper.UserMapper">
<select id="findAllUsers" resultType="com.example.mybatis.dto.UserTO">
SELECT * FROM users
</select>
<select id="findUserById" parameterType="int" resultType="com.example.mybatis.dto.UserTO">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
3.7 서비스 클래스
package com.example.mybatis.service;
import com.example.mybatis.dto.UserTO;
import com.example.mybatis.mapper.UserMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public List<UserTO> getAllUsers() {
return userMapper.findAllUsers();
}
public UserTO getUserById(int id) {
return userMapper.findUserById(id);
}
}
3.8 컨트롤러 클래스
package com.example.mybatis.controller;
import com.example.mybatis.dto.UserTO;
import com.example.mybatis.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<UserTO> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public UserTO getUserById(@PathVariable int id) {
return userService.getUserById(id);
}
}
⇒ mapper.xml 사용
package com.example.mybatis.mapper;
import com.example.mybatis.dto.UserTO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
List<UserTO> findAllUsers();
UserTO findUserById(int id);
}
- UserMapper Interface 수정
- @Select 어노테이션 제거
4. MyBatis의 장점과 단점
4.1 장점
- SQL 중심 제어 :
- SQL을 직접 작성해서 복잡한 쿼리 처리에 적합.
- 유연성 :
- ORM처럼 제약이 많지 않고, 개발자가 모든 SQL을 제어 가능.
- 자동 매핑 :
- XML과 Java 객체 간 매핑이 간단.
- 동적 SQL 지원 :
- XML 태그를 사용해 조건부, 반복 쿼리를 작성 가능
4.2 단점
- SQL 직접 작성 :
- SQL을 직접 작성해야 해서 코드가 길어질 수 있음
- 유지보수 :
- SQL과 비즈니스 로직이 분리되지만, SQL 파일 관리가 많아지면 유지보수가 어려울 수 있음.
- ORM 기능 부족 :
- 엔티티 간 관계를 자동으로 처리하는 기능이 부족 (JPA보다 낮은 수준의 데이터 매핑)
5. MyBatis와 JPA 비교
특징 | MyBatis | JPA (Hibernate) |
쿼리 제어권 | SQL을 직접 작성 | SQL 자동 생성 |
성능 | SQL 최적화 가능 | ORM으로 인해 복잡한 쿼리 성능 저하 가능 |
복잡한 쿼리 처리 | 복잡한 쿼리에 적합 | 복잡한 쿼리 작성 시 번거로움 |
학습 곡선 | 낮음 | 비교적 높음 |
엔터티 관계 처리 | 수동 처리 필요 | 자동 처리 |
6. 공식 문서 및 참고 자료
- MyBatis 공식 문서: MyBatis Documentation
- MyBatis-Spring 공식 문서: MyBatis-Spring Documentation
- MyBatis GitHub 레포지토리: MyBatis GitHub
'Spring' 카테고리의 다른 글
MyBatis - SqlSession (0) | 2024.12.16 |
---|---|
MyBatis - Mapper XML (1) | 2024.12.15 |
RowMapper와 BeanPropertyRowMapper (1) | 2024.12.15 |
JDBC API - JDBC Template (1) | 2024.12.14 |
Spring Boot - JDBC 연결과 DataSource(MariaDB) (0) | 2024.12.14 |