레이블이 mybatis인 게시물을 표시합니다. 모든 게시물 표시
레이블이 mybatis인 게시물을 표시합니다. 모든 게시물 표시

2011년 10월 13일 목요일

How to use mybatis mapper


mybatis를 이용하면 XML 매핑 파일을 작성하는 대신 annotation 이용하여 개발이 가능하다.


SQL 코드를 클래스로부터 분리하여 별도의 리소스(sqlmap xml)파일로 관리할 수 있도록 하는 방식에서
인터페이스 안에 매핑정보를 넣어야 하는 게 올바른 방향인지는 궁금하다.

쿼리가 변경되면 인터페이스를 재 컴파일해서 올려야 할 듯.
아무튼 간단히 개발하는 곳에서는 적용해볼만 한듯해서 관련 소스를 올려둔다.

  • 스프링 설정 파일

    스프링 설정 파일에서는 dataSource, sqlSessionFactory 및 매퍼 인터페이스를 지정해야 한다.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
      <context:component-scan base-package="com.archnal.samples.mybatis"/>
      
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
      </bean>
      <context:property-placeholder location="spring/jdbc.properties" />
    
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
      </bean>
      <bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface"
          value="com.archnal.samples.mybatis.mapper.AccountMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
      </bean>
    
    
    </beans>
    
  • Mapper 인터페이스

    Mapper 인터페이스에서는 mybatis에서 제공하는 @Select, @Insert 등의 annotation을 이용하여 쿼리를 작성할 수 있다.

    package com.archnal.samples.mybatis.mapper;
    
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Param;
    import org.apache.ibatis.annotations.Select;
    
    import com.archnal.samples.mybatis.dto.Account;
    
    public interface AccountMapper {
      String INSERT = "INSERT INTO tbl_account (name, email) values (#{name}, #{email})";
    
      
      @Select("SELECT * FROM tbl_account WHERE email = #{email}")
      Account getByEmail(@Param("email") String email);
      
      @Insert(INSERT)
      void insert(Account account);
    }
    
    
  • test 클래스

    아래의 소스 코드에서 처럼 실행하면 실제로 데이터베이스에서 값을 읽어 오거나 추가시킬 수 있다.

    package com.archnal.samples.mybatis.mapper;
    
    import javax.annotation.Resource;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.test.annotation.Rollback;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.context.transaction.TransactionConfiguration;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.archnal.samples.mybatis.dto.Account;
    
    @ContextConfiguration(locations={"classpath*:spring/*-config.xml"})
    @RunWith(SpringJUnit4ClassRunner.class)
    @TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
    @Transactional(readOnly=true)
    public class AccountMapperTest {
      @Resource(name="accountMapper")
      AccountMapper accountMapper;
      
      @Test
      public void testGetByEmail() throws Exception {
        String email = "crexxx@gmail.com";
        Account account = accountMapper.getByEmail(email);
        
        System.out.println("account: " + account);
      }
      
      @Test
      @Rollback(true)
      @Transactional(readOnly=false)
      public void testInsert() throws Exception {
        String name = "ko";
        String email = "koxxx@gmail.com";
        
        Account account = new Account();
        account.setName(name);
        account.setEmail(email);
        
        accountMapper.insert(account);
        
      }
    }