MyBatis 실전 사용 방법

MyBatis vs JPA

목록 보기
5/6

복잡한 쿼리는 XML 방식으로, 간단한 쿼리는 애너테이션 방식으로 처리하면 효율적인 개발이 가능.

단계

설정: 의존성 추가 및 데이터베이스 연결 설정.
Mapper 인터페이스: SQL 작성(애너테이션 또는 XML).
DTO/VO 설계: 쿼리 결과를 매핑할 클래스 설계.
서비스 계층: MyBatis 호출 로직 작성.
컨트롤러 설계: 클라이언트 요청 처리.

1.의존성

  1. build.gradle에 의존성 추가
dependencies {
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2'
    implementation 'mysql:mysql-connector-java' // DB 커넥터
}

2.application.yml 또는 application.properties 파일에 데이터베이스 설정을 추가

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

mybatis:
  mapper-locations: classpath:mapper/*.xml  # XML 파일 위치
  type-aliases-package: com.example.domain  # DTO나 VO 패키지 위치

2.엔티티 및 DTO 설계

MyBatis는 직접 SQL 결과를 매핑하므로, 필요한 VO 또는 DTO 클래스를 만들어야 합니다.

package com.example.domain;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String email;
    private String role;
}

3. Mapper 인터페이스 설계

어노테이션 방식 - 간단한 쿼리

package com.example.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import com.example.domain.User;

@Mapper
public interface UserMapper {

    // 사용자 ID로 검색
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(@Param("id") Long id);

    // 모든 사용자 검색
    @Select("SELECT * FROM users")
    List<User> getAllUsers();
}

xml 파일 방식-복잡한 쿼리

mapper 인터페이스
UserMapper.java에서 XML의 namespace와 메서드가 매칭된다.

@Mapper
public interface UserMapper {
    User getUserById(@Param("id") Long id);

    List<User> getAllUsers();

    List<User> getUsersByFilter(Map<String, Object> params);
}

xml 파일(위치 : resources/mapper/UserMapper.xml)

<mapper namespace="com.example.mapper.UserMapper">
    <!-- 사용자 ID로 검색 -->
    <select id="getUserById" parameterType="long" resultType="com.example.domain.User">
        SELECT * FROM users WHERE id = #{id}
    </select>

    <!-- 사용자 목록 검색 -->
    <select id="getAllUsers" resultType="com.example.domain.User">
        SELECT * FROM users
    </select>

    <!-- 동적 쿼리 예제 -->
    <select id="getUsersByFilter" parameterType="map" resultType="com.example.domain.User">
        SELECT * FROM users
        WHERE 1=1
        <if test="username != null">
            AND username = #{username}
        </if>
        <if test="email != null">
            AND email = #{email}
        </if>
    </select>
</mapper>

Mybatis의 동적쿼리?
XML의 , 등을 사용하여 다양한 동적 쿼리를 작성할 수 있음.

<choose>
    <when test="role == 'admin'">
        AND role = 'admin'
    </when>
    <otherwise>
        AND role != 'admin'
    </otherwise>
</choose>

4. 컨트롤러 작성

package com.example.controller;

import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/filter")
    public List<User> getUsersByFilter(@RequestParam Map<String, Object> filters) {
        return userService.getUsersByFilter(filters);
    }
}
profile
내가 있는 그 조직에서 가장 성실하기만 하자

0개의 댓글