MyBatis - Mapper 인터페이스 활용 ( @Select )

TopOfTheHead·2026년 4월 20일

MyBatis / JPA

목록 보기
2/10

기존 방식의 경우 MyBatis의 각 도메인 마다 Mapper.xml 파일을 정의하며, 이에 전역설정파일(= mybatis-config.xml)의 <mappers>에서 <mapper>로서 각각 추가적으로 정의했어야 했다.
도메인을 추가 시 마다 개발자가 일일이 전역설정파일을 수정해야하는 단점이 존재
인터페이스 방식을 통해 해결이 가능

Mapper 인터페이스 정의
Mapper.xml파일SQL매핑태그바인딩추상메서드를 정의

Mapper.xml 파일<mapper namespace="인터페이스명"> 등록 시 MyBatis에 의해 해당 Mapper 인터페이스를 자동으로 스캔하여 가져와서 등록

추상 메서드의 경우 <select id="test">id=추상메서드명 지정 시 자동으로 바인딩

public interface TestMapper {
	Integer test();
}

@Select("SELECT문")
Mapper.xml파일SQL매핑태그를 따로 지정할 필요없이, 인터페이스 추상메서드에 간단하게 선언하여 활용하는 방식
어노테이션에 선언된 SQL 쿼리가 바로 실행됨

。단, 동적 쿼리는 지원되지 않는 단점이 존재

public interface TestMapperV3 {
	@Select("select 1") 
	Integer test();
}

Mapper.xml 파일 정의
Mapper Interface추상메서드바인딩 되어 실제 실행될 SQL매핑태그를 작성

<select>id="" 속성인터페이스 추상메서드 명과 동일하게 설정
▶ 설정 시 인터페이스 추상메서드SQL매핑태그는 서로 바인딩되어 연동되므로, 추상메서드 호출 시 SQL매핑태그에 정의된 SQL문이 실행

。반드시 Mapper 인터페이스미러링되는 resources 이하 디렉토리에서 Mapper 인터페이스와 동일한 파일명으로 등록해야한다.
ex ) java/mapper/TestMapper.Interface인 경우 resources/mapper/TestMapper.xml로 설정

<mapper>namespace = "" 속성src/main/java 기준 절대경로로 입력
▶ 등록 시 MyBatisMapper 인터페이스를 자동으로 스캔하여 식별

<?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="mapper.TestMapper">
    <select id="test" resultType="int">
        SELECT 1;
    </select>
</mapper>

XML 전역 설정 파일 정의
<mapper><package name="디렉토리 경로">를 통해 Mapper 인터페이스가 위치한 디렉토리 경로를 설정
src/main/java 기준 Mapper 인터페이스가 위치한 디렉토리 경로를 입력
ex ) mapper = src/main/java/mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="exp1">
        <environment id="exp1">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name = "driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name = "url" value="jdbc:mysql://localhost:3304/mybatis_shop"/>
                <property name = "username" value="root"/>
                <property name = "password" value="wjd747"/>
            </dataSource>
        </environment>
    </environments>
<!--  Mapper Registry 정의  -->
    <mappers>
<!--    Package 태그는 반드시 name 속성을 포함 및 src/main/java 기준 Mapper 인터페이스가 위치한 패키지명 입력    -->
        <package name="mapper"/>
    </mappers>
</configuration>

인터페이스 구현체 생성 및 Query 실행
SqlSession객체.getMapper(인터페이스.class); : 클래스리터럴을 통해 Mapper 인터페이스클래스 타입을 정의한 인터페이스 구현체 생성
▶ 해당 메타데이터를 이용하여 인터페이스추상 메서드를 사용하도록 설정

추상메서드 호출 시 바인딩Mapper.xml 파일SQL매핑태그SQL문이 자동 실행

public class SessionFactory {
	public static void main(String[] args) throws IOException {
		String xmlFileFir = "mybatis-config.xml";
		InputStream resourceAsStream = Resources.getResourceAsStream(xmlFileFir);
		SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
		try(
			SqlSession sqlSession = build.openSession()
		){
			TestMapper mapper = sqlSession.getMapper(TestMapper.class);
			Integer test = mapper.test();
			System.out.println(test);
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}
profile
공부기록 블로그

0개의 댓글