SpringBoot - MyBatis를 통한 MySQL 연동

Woody·2022년 1월 2일
post-thumbnail

항상 개발보다 환경설정이 피곤하기에 입사 후 개발했던 파일럿 프로젝트의 코드를 참고용으로 기록해두려고 한다.

pom.xml

의존성 객체 추가

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.2.0</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

mybatis-config.xml

mapper 가 스캔할 경로들 미리 설정

<?xml version="1.0" encoding="UTF-8" ?>
<!--
       Copyright 2015-2016 the original author or authors.
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <package name="com.test.board.front.model"/>
        <package name="com.test.board.admin.model"/>
    </typeAliases>
    <mappers>
		<!-- FRONT -->
        <mapper resource="mybatis/sql/front/BoardMapper.xml"/>
        <mapper resource="mybatis/sql/front/UserMapper.xml"/>
        <mapper resource="mybatis/sql/front/QnAMapper.xml"/>

        <!-- ADMIN -->
        <mapper resource="mybatis/sql/admin/AdminUserMapper.xml"/>
        <mapper resource="mybatis/sql/admin/AuthMapper.xml"/>
    </mappers>
</configuration>

application.properties

DB Connection을 위한 환경 설정

spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=0000

mybatis.config-location=classpath:mybatis-config.xml

spring.servlet.multipart.maxFileSize=5MB
spring.servlet.multipart.maxRequestSize=5MB

image.root.path=/images
image.default.path=/default

AdminUserMapper.java

인터페이스를 @Mapper로 등록

@Mapper
public interface AdminUserMapper {
    AdminUser login(AdminUser param);

    int doubleCheck(String id);

    int join(AdminUser user);

    List<AdminUser> adminUserList(AdminUser param);

    AdminUser detail(int pk);

    int deleteAdmin(AdminUser adminUser);

    int updateAdmin(AdminUser adminUser);
}

AdminUserMapper.xml

mapper namespace="" : 매우 중요! 패키지명 반드시 정확히 일치해야 함.

<?xml version="1.0" encoding="UTF-8" ?>
<!--
       Copyright 2015-2016 the original author or authors.
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.test.board.admin.mapper.AdminUserMapper">

    <select id="adminUserList" parameterType="AdminUser" resultType="AdminUser">
        SELECT  pk, id, name, date_format(joinDate,'%Y-%m-%d %H:%i:%s') as joinDate,
                del, date_format(delDate,'%Y-%m-%d %H:%i:%s') as delDate
        FROM  AdminUser
        WHERE 1=1
        <if test="id != null and id != ''">
            AND id LIKE CONCAT('%', #{id}, '%')
        </if>

        <if test="startDt != null and startDt != ''">
            <if test="endDt != null and endDt != ''">
                AND date_format(joinDate,'%Y-%m-%d') BETWEEN #{startDt} AND #{endDt}
            </if>
        </if>

        ORDER BY joinDate desc
    </select>

    <select id="detail" parameterType="int" resultType="AdminUser">
        SELECT  pk, id, name, date_format(joinDate,'%Y-%m-%d %H:%i:%s') as joinDate,
        del, date_format(delDate,'%Y-%m-%d %H:%i:%s') as delDate
        FROM  AdminUser
        WHERE pk = ${pk}
    </select>

    <select id="login" parameterType="AdminUser" resultType="AdminUser">
        SELECT
               pk, id, password, del
        FROM   AdminUser
        WHERE  id = #{id}
    </select>

    <select id="doubleCheck" parameterType="String" resultType="int">
        SELECT count(pk)
        FROM   AdminUser
        WHERE  id = #{id}
    </select>

    <insert id="join" parameterType="AdminUser" useGeneratedKeys="true" keyProperty="pk" keyColumn="pk">
        INSERT INTO AdminUser (
            id,
            password,
            name,
            del,
            joinDate
        )
        VALUES(
            #{id},
            #{password},
            #{name},
            'N',
            now()
        )
    </insert>

    <update id="deleteAdmin" parameterType="AdminUser">
        UPDATE
            AdminUser
        SET
            del='Y',
            delDate = NOW()
        WHERE 1=1
        <if test="adminPks != null">
            AND pk IN
            <foreach item="item" index="index" open="(" close=")" collection="adminPks">
                <if test="index != null and index != ''">,</if> #{item}
            </foreach>
        </if>
    </update>

    <update id="updateAdmin" parameterType="AdminUser">
        UPDATE
            AdminUser
        SET
            name=#{name}
            <if test="password != null and password != ''">
                , password = #{password}
            </if>
        WHERE pk = #{pk}
    </update>


</mapper>
profile
If the wind will not serve, take to the oars

0개의 댓글