MyBatis를 까먹지 말자

Junkyu_Kang·2024년 4월 23일

흠 요즘 jpa만 쓰다보니까 MyBatis가 가물가물하다..
하지만 까먹으면 안되니까 다시 설명을 써보자

1. 프로젝트 설정을 해야지(의존성 추가를 해야해)

Maven

<!-- Spring Boot Starter for MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

Gradle

implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0'

아무리 생각해도 Gradle이 편해...

2. 데이터베이스 설정(application.properties or application.ym)

spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3. Mapper Interface 및 XML 파일 작성

Mapper Interface

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Mapper;
import com.example.demo.model.User;

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

XML 파일 작성(resources/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.demo.mapper.UserMapper">
    <select id="findUserById" resultType="com.example.demo.model.User">
        SELECT * FROM users WHERE id = #{id}
    </select>
</mapper>

4. Service와 Controller 구현

서비스 구현

package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(int id) {
        return userMapper.findUserById(id);
    }
}

컨트롤러 구현

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.User;
import com.example.demo.service.UserService;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

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

여기서 뭐.. 문제라기보단 다른 점은 폴더 구조를 어떻게 할지

나는 보통

controller
dao
dto
service
serviceImpl
repository
repositoryImpl

구조로 하긴 하는데 흠 이건 사람마다 다르니까.. 아무튼간 포스팅 끝!

profile
강준규

0개의 댓글