본문 바로가기

MyBatis

Java - Mybatis ( 일반 DML 호출 )

필요 lib : mybatis.jar   ,   ojdbc6 , 톰캣






# 개요 
      Java로 Mybatis사용시 데이터를 가져오는 방식은 to방식과 Map방식이 있다.
      이 두가지 방법을 구현해 보겠다.
    


1. to방식
to방식은 새로 하나 추가되서 두가지가 있는데 xml이용과 인터페이스이용법이다.

1) xml이용시
        parameter로 사용될시 대소문자구분( 이유는 #{seq} 와 #{SEQ}는 다름 )
        result로 사용시 대소문자 구분안함

2) 인터페이스이용시
        매퍼.xml이 사라지고 인터페이스에서 어노테이션에 쿼리를 주는방식
        



2. Map방식 ( hashmap )

Test.java    --    메인메서드
import java.io.*;
import java.util.HashMap;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {

public static void main(String[] args) {
       SqlSession session = null;
       
       try {
              String resource = "mybatis-config.xml";
              InputStream inputStream = Resources.getResourceAsStream(resource);
              SqlSessionFactory sqlSessionFactory = 
                            new  SqlSessionFactoryBuilder().build(inputStream);
              
              session = sqlSessionFactory.openSession();
       
              // HashMap방식
              HashMap<String, Object> toMap = new HashMap<String, Object>();
              toMap.put("SEQ", 1);
              
              
              HashMap<String, Object> fromMap 
                        =  session.selectOne("BoardMapper.selectBoardToMap", toMap);
              System.out.println( fromMap.get("SEQ") );
              System.out.println( fromMap.get("TITLE") );
              System.out.println( fromMap.get("CONTENT") );
              System.out.println( fromMap.get("HIT_CNT") );
              
              
              // TO방식
              Board board = new Board();
              board.setSeq(1);
              
              Board resutBoard 
                =  (Board)session.selectOne("BoardMapper.selectBoardToBean", board);
              
              System.out.println( resutBoard.getSeq() );
              System.out.println( resutBoard.getTitle() );
              System.out.println( resutBoard.getContent() );
              System.out.println( resutBoard.getHitCnt() );
              
              
              // TO방식 신규( BoardMapper.xml대신 BoardMapper인터페이스에 어노테이션사용 )
              // 장 : 리턴타입에 대해 형변환 필요없음
              //            , 문자열에 의존하지않음???
              // 단 : 오히려 쿼리복잡해지면 불편할듯?
              BoardMapper mapper = session.getMapper(BoardMapper.class);
              Board bo = mapper.selectBoard(1);
              
              System.out.println( bo.getSeq() );
              System.out.println( bo.getTitle() );
              System.out.println( bo.getContent() );
              System.out.println( bo.getHitCnt() );
              
       } catch (Exception e) {
              System.out.println(e.getMessage());
       }finally {
              session.close();
       }
       System.out.println("종료");
}
}


mybatis-config.xml   --마이바티스설정파일
    (원래 프로퍼티스로 password등을 주는데 어떻게 하는지 몰겟다.걍 바로줘버림)
<?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>
       <typeAliases>
              <typeAlias  alias="Board" type="Board"/>
       </typeAliases>
       <environments default="development">
              <environment id="development">
                     <transactionManager type="JDBC" />
                     <dataSource type="POOLED">
                           <property name="driver"
                                  value="oracle.jdbc.driver.OracleDriver" />
                           <property name="url"
                                  value="jdbc:oracle:thin:@localhost:1521:orcl" />
                           <property name="username" value="scott" />
                           <property name="password" value="tiger" />
                     </dataSource>
              </environment>
       </environments>
       <mappers>
              <mapper resource="BoardMapper.xml" />
       </mappers>
       
</configuration>



BoardMapper.xml
<?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="BoardMapper">

       <select id="selectBoardToMap" parameterType="hashmap" resultType="hashmap">
              SELECT SEQ, TITLE, CONTENT , HIT_CNT
              FROM BOARD
              WHERE SEQ = #{SEQ}
       </select>

       <select id="selectBoardToBean" parameterType="Board" resultType="Board">
              SELECT SEQ, TITLE, CONTENT , HIT_CNT as hitcnt
              FROM BOARD
              WHERE SEQ = #{seq}   
                <!-- 파라미터로사용시 대소문자구분, result는  대소문자구분X -->
       </select>
       
</mapper>



BoardMapper.java    -- 매퍼.xml사용안하고 매퍼.class사용시
import org.apache.ibatis.annotations.Select;
/*     XML매퍼(BardMapper.xml)를 작성안해도됨
*
* */
public interface BoardMapper {
       @Select("SELECT "
                     + "SEQ, TITLE, CONTENT, HIT_CNT as hitcnt "
                     + "FROM BOARD "
                     + "WHERE SEQ = #{SEQ}")
       Board selectBoard(int seq);
}


Board.java
private int seq, hitCnt;
private String title,content;