MyBatis의 다양한 설정 방식 분석

  1. 전통적인 XML 기반 설정 MyBatis 초기 설계에서 가장 기본적인 방식은 SQL을 별도의 XML 파일에 정의하고, 이를 구성 파일을 통해 로드하는 구조입니다. 이 방식은 명시적이고 직관적이지만, 설정 파일이 많아지면 관리가 어려워집니다.
public class XmlMain {
    public static void main(String[] args) {
        try (InputStream configStream = Resources.getResourceAsStream("mybatis-config.xml");
             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configStream);
             SqlSession session = factory.openSession()) {

            Blog blog = session.selectOne("com.example.mapper.BlogMapper.selectBlog", 1);
            System.out.println(blog);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

데이터베이스 매핑 정보는 BlogMapper.xml 파일로 분리되며, 다음과 같은 형식으로 작성됩니다:

<mapper namespace="com.example.mapper.BlogMapper">
    <resultMap id="blogResult" type="com.example.entity.Blog">
        <result property="id" column="ID"/>
        <result property="userName" column="username"/>
        <result property="date" column="date"/>
        <result property="score" column="score"/>
    </resultMap>

    <select id="selectBlog" resultMap="blogResult" parameterType="int">
        SELECT * FROM a_user WHERE id = #{id}
    </select>
</mapper>

전체 설정은 mybatis-config.xml에 정의되며, 데이터 소스와 환경 설정이 포함됩니다.

  1. XML 없이 애노테이션 기반 설정 XML을 완전히 제거하고, 인터페이스에 애노테이션을 사용해 SQL을 직접 정의하는 방식입니다. 이는 코드 중심 접근이며, 간결성과 유지보수성을 높이는 데 유리합니다.
public interface BlogMapper {
    @Select("SELECT * FROM a_user WHERE id = #{id}")
    Blog selectById(int id);
}

설정은 자바 코드로 직접 구성합니다:

public class MainTest {
    public static void main(String[] args) {
        DataSource dataSource = createDataSource();
        Environment env = new Environment("development", new JdbcTransactionFactory(), dataSource);
        Configuration config = new Configuration(env);
        config.addMappers("com.example.mapper");

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
        
        try (SqlSession session = factory.openSession()) {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog result = mapper.selectById(1);
            System.out.println("[RESULT] " + result);
        }
    }

    private static DataSource createDataSource() {
        Properties props = new Properties();
        props.setProperty("driver", "com.mysql.cj.jdbc.Driver");
        props.setProperty("url", "jdbc:mysql://localhost:3306/order?allowMultiQueries=true");
        props.setProperty("username", "root");
        props.setProperty("password", "1234");

        PooledDataSourceFactory factory = new PooledDataSourceFactory();
        factory.setProperties(props);
        return factory.getDataSource();
    }
}

이 방식은 mybatis-config.xml이 필요 없으며, 순수 자바 코드로 모든 설정이 가능합니다.

  1. Spring 통합 방식 (MyBatis-Spring) Spring 프레임워크와 결합하여, 스프링의 의존성 주입과 빈 관리를 활용하는 방식입니다. 이는 개발 생산성과 테스트 용이성을 크게 향상시킵니다.
@Configuration
@MapperScan("com.example.mapper")
public class DatabaseConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean
    public DataSource dataSource() {
        // 동일한 방법으로 DataSource 생성
        Properties props = new Properties();
        props.setProperty("driver", "com.mysql.cj.jdbc.Driver");
        props.setProperty("url", "jdbc:mysql://localhost:3306/order?allowMultiQueries=true");
        props.setProperty("username", "root");
        props.setProperty("password", "1234");

        PooledDataSourceFactory factory = new PooledDataSourceFactory();
        factory.setProperties(props);
        return factory.getDataSource();
    }
}

서비스 클래스에서는 단순히 @Autowired로 매퍼를 주입하면 됩니다:

@Service
public class BlogService {
    @Autowired
    private BlogMapper blogMapper;

    public void executeQuery() {
        Blog blog = blogMapper.selectById(1);
        System.out.println(blog);
    }
}
  1. Spring Boot 자동 구성 방식 (mybatis-spring-boot-starter) 최근에는 mybatis-spring-boot-starter를 통해 거의 모든 설정을 자동 처리할 수 있습니다. application.yml에 간단한 설정만 추가하면 됩니다.
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/order?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8
    username: root
    password: 1234

mybatis:
  type-aliases-package: com.example.entity
  mapper-locations: classpath:mapper/*.xml

dependencies에 다음을 추가하면 자동으로 설정됩니다:

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

이 방식은 "약속에 따라 구성"하는 원칙을 실현하며, 개발자는 대부분의 설정을 생략할 수 있습니다.

태그: MyBatis Spring Boot XML Configuration annotation mapping MyBatis-Spring

9월 29일 17:03에 게시됨