본문 바로가기
Mybatis/MyBatis + Spring 연동

Spring Boot에서 MyBatis 설정하기

by DEVLIB 2025. 4. 17.
728x90

1. 프로젝트 구조 및 의존성

Gradle 사용 시 (build.gradle)

dependencies {
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2'
    implementation 'mysql:mysql-connector-j:8.0.33'
}

Maven 사용 시 (pom.xml)

<dependencies>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.2</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.0.33</version>
  </dependency>
</dependencies>

2. application.yml 또는 .properties 설정

application.yml 예시

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: yourpassword
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:/mappers/**/*.xml
  type-aliases-package: com.example.project.domain
  configuration:
    map-underscore-to-camel-case: true

3. Mapper 인터페이스 + XML 파일 작성

UserMapper.java

@Mapper
public interface UserMapper {
    User findById(int id);
}

UserMapper.xml

<mapper namespace="com.example.project.mapper.UserMapper">
  <select id="findById" resultType="User">
    SELECT * FROM users WHERE id = #{id}
  </select>
</mapper>
>
  • XML 파일은 /resources/mappers/에 위치해야 함

4. DTO (도메인 객체) 작성

public class User {
    private int id;
    private String name;
    private String email;
    // getter/setter
}

5. Mapper 스캔 설정 방법 2가지

방법 1: @MapperScan 사용

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

방법 2: 각 Mapper에 @Mapper 어노테이션 추가

@Mapper
public interface UserMapper { ... }

6. 서비스에서 사용하기

@Service
@RequiredArgsConstructor
public class UserService {

    private final UserMapper userMapper;

    public User getUser(int id) {
        return userMapper.findById(id);
    }
}

Spring이 자동으로 Mapper를 주입해줍니다.


마무리 점검 체크리스트

항목
의존성 추가 완료
DB 정보 설정 완료 (application.yml)
Mapper 인터페이스 & XML 일치 여부 (namespace, id)
@MapperScan 또는 @Mapper 적용 여부
DTO 클래스와 컬럼명 일치 여부

응용

  • 게시판, 회원가입, 로그인 기능 구현
  • 검색 + 페이징 + 정렬 기능 추가
  • 트랜잭션 설정 및 Mapper 분리 구조화
LIST