본문 바로가기

IT/Spring

[Spring Boot] MariaDB 연동 및 Mybatis 사용하기

안녕하세요. 밤둘레입니다.

MariaDB 연동 및 Mybatis 사용법 정리 글입니다.

Spring Boot Project를 생성하려면 아래 URL로 이동해서 프로젝트를 생성해주세요.

https://start.spring.io/

위와 같이 Spring Boot 프로젝트를 생성 하면 됩니다.


1. pom.xml

...
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
...

2. application.properties

spring.datasource.hikari.maximum-pool-size = 4
spring.datasource.url = URL
spring.datasource.username = username
spring.datasource.password = password

mybatis.type-aliases-package = com.example.bamdule.model
mybatis.mapper-locations = mapper/xml/*.xml  
  • mybatis.type-aliases-package : Model Class Package 경로를 적어주시면 됩니다.
    사용하지 않으면 생략 해도 됩니다. 대신 mapper.xml 작성 시, Model의 모든 경로를 적어주셔야 합니다.
  • mybatis.mapper-locations : mapper.xml 경로를 적어주시면 됩니다.

3. Model Class 생성

import java.time.LocalDateTime;

public class Student {

    private Integer id;
    private String name;
    private String code;
    private LocalDateTime saveDate = LocalDateTime.now();
	
    //setter, getter, toString 생략
	
}

4. Mapper interface 생성

import com.example.bamdule.model.Student;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {

    public List<Student> findList();

    public Student findOneByCode(String codes);

    public void save(Student student);

    public void update(Student student);

    public void deleteById(Integer id);
}

5. mapper-student.xml

<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.bamdule.mapper.StudentMapper">
    <select id="findList" resultType="student">
        SELECT 
            id,
            name,
            code,
            save_date as 'saveDate'
        FROM student
    </select>
    
    <select id="findOneByCode" parameterType="String" resultType="student">
        SELECT
            id,
            name,
            code,
            save_date as 'saveDate'
        FROM student
        WHERE code = #{code}
    </select>    
    
    <insert id="save" parameterType="student">
        INSERT INTO student (
            name,
            code,
            save_date
        ) VALUES (
            #{name},
            #{code},
            #{saveDate}
        )
    </insert>
    
    <update id="update" parameterType="student">
        UPDATE student
        SET 
            name = #{name},
            code = #{code},
            save_date = #{saveDate}
        WHERE id = #{id}
    </update>
    
    <delete id = "deleteById" parameterType="int">
        DELETE FROM student WHERE id = #{id}
    </delete>
</mapper>
  • src/main/resources/mapper/xml/mapper-student.xml 위치에 생성해주시면 됩니다.
  • DB Query를 정의해 놓은 xml입니다.
  • namaspace는 Mapper Interface Package를 적어주시면 됩니다.

6. Table Create Query

CREATE TABLE `student` (
	`id` INT(11) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(20) NULL DEFAULT NULL,
	`save_date` DATETIME NULL DEFAULT NULL,
	`code` VARCHAR(30) NOT NULL,
	PRIMARY KEY (`id`),
	UNIQUE INDEX `CODE_UK` (`code`)
)

Test 하기전 Student Table을 생성해줍니다.


7. Test

import com.example.bamdule.mapper.StudentMapper;
import com.example.bamdule.model.Student;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
class BamduleApplicationTests {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    void 학생_생성() {
        String code = "S20200102154530";
        String name = "Son";
        Student student = studentMapper.findOneByCode(code);

        if (student == null) {
            student = new Student(name, code);
            studentMapper.save(student);
        } else {
            student.setSaveDate(LocalDateTime.now());
            studentMapper.update(student);
        }
    }

    @Test
    void 학생_리스트_출력() {
        studentMapper.findList().forEach(data -> System.out.println(data));
    }

}

8. 결과

위와 같이 출력되었다면 성공입니다.


도움이 되셨다면 공감 한번씩 눌러주시면 감사하겠습니다.