Mybatis5: Table Join

업데이트:
2 분 소요

비트캠프 서초본원 엄진영 강사님의 수업을 듣고 정리했습니다.


Mybatis5: Table Join

1. 조인 하기 전

  • 게시글과 첨부파일의 데이터를 확인하는데, 조인을 사용하기 전에는 데이터를 따로 조회해야 한다.
  • 즉 게시글 테이블에서 데이터를 조회하는 SQL문과 첨부파일 테이블에서 데이터를 조회하는 SQL문을 두 번 실행해야 한다.
// 조인 데이터 가져오기 - 각 테이블의 데이터를 별도로 가져오기

public class Exam0110 {
  public static void main(String[] args) throws Exception {
    InputStream inputStream = Resources.getResourceAsStream(//
        "com/eomcs/mybatis/ex04/mybatis-config.xml");
    SqlSessionFactory factory = //
        new SqlSessionFactoryBuilder().build(inputStream);

    SqlSession sqlSession = factory.openSession();

    Board board = sqlSession.selectOne("BoardMapper.selectBoard", 7);
    // 샘플 데이터(x_board) 확인 후 테스트하기

    System.out.println("[게시글 조회]");
    System.out.printf("번호: %d\n", board.getNo());
    System.out.printf("제목: %s\n", board.getTitle());
    System.out.printf("내용: %s\n", board.getContent());
    System.out.printf("등록일: %s\n", board.getRegisteredDate());
    System.out.printf("조회수: %d\n", board.getViewCount());
    System.out.println();

    List<AttachFile> files = sqlSession.selectList("BoardMapper.selectFile", 1);

    System.out.println("[첨부파일]");
    for (AttachFile file : files) {
      System.out.printf("%d, %s\n", file.getNo(), file.getFilePath());
    }
    sqlSession.close();
  }
}
  • BoardMapper.xml에 게시글을 조회하는 select문과 첨부파일을 조회하는 select문이 포함되어있다.
<?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">

  <resultMap type="Board" id="BoardMap">
    <id column="board_id" property="no"/>
    <!-- 
    <result column="title" property="title"/>
    -->
    <result column="contents" property="content"/>
    <result column="created_date" property="registeredDate"/>
    <result column="view_count" property="viewCount"/>
  </resultMap>
  
  <resultMap type="AttachFile" id="AttachFileMap">
    <id column="board_file_id" property="no"/>
    <result column="file_path" property="filePath"/>
    <result column="board_id" property="boardNo"/>
  </resultMap>
  
  <select id="selectBoard" resultMap="BoardMap" parameterType="int">
    select 
      board_id,
      title, 
      contents, 
      created_date,
      view_count 
    from x_board
    <if test="no != null">
      where board_id = #{no}
    </if>
  </select>
  
  <select id="selectFile" 
          resultMap="AttachFileMap" 
          parameterType="int">
    select 
      board_file_id,
      file_path
    from x_board_file
    where board_id = #{no}
  </select>

</mapper>

2. 조인 하기

  • 조인을 사용하면 한 테이블 안에 다른 테이블의 정보가 들어 있다. 그래서 따로 select문을 실행할 필요가 없다.
  • 아 경우에는 게시글 객체 안에 첨부파일 객체가 들어있기 때문에 SQL문을 한 번만 실행하면 된다.
public class Exam0120 {
  public static void main(String[] args) throws Exception {
    InputStream inputStream = Resources.getResourceAsStream(
        "com/eomcs/mybatis/ex04/mybatis-config.xml");
    SqlSessionFactory factory = 
        new SqlSessionFactoryBuilder().build(inputStream);

    SqlSession sqlSession = factory.openSession();

    Board board = sqlSession.selectOne("BoardMapper2.selectBoardWithFile", 1);

    System.out.println("[게시글 조회]");
    System.out.printf("번호: %d\n", board.getNo());
    System.out.printf("제목: %s\n", board.getTitle());
    System.out.printf("내용: %s\n", board.getContent());
    System.out.printf("등록일: %s\n", board.getRegisteredDate());
    System.out.printf("조회수: %d\n", board.getViewCount());
    System.out.println();

    System.out.println("[첨부파일]");
    for (AttachFile file : board.getFiles()) {
      System.out.printf("%d, %s\n", file.getNo(), file.getFilePath());
    }

    // 구동원리:
    // ResultSet rs = stmt.executeQuery(
    // "select"
    // " b.board_id,"
    // + " b.title, "
    // + " b.contents, "
    // + " b.created_date,"
    // + " b.view_count,"
    // + " f.board_file_id,"
    // + " f.file_path "
    // + "from x_board b "
    // + " left outer join x_board_file f on b.board_id=f.board_id"
    // + "where b.board_id = 1");
    //
    // ArrayList<Board> boardList = new ArrayList<>();
    // int boardNo = 0;
    // Board board = null;
    // ArrayList<AttachFile> files = null;
    // while (rs.next()) {
    // if (boardNo != rs.getInt("board_id")) {
    // board = new Board();
    // board.setNo(rs.getInt("board_id"));
    // board.setTitle(rs.getString("title"));
    // board.setContent(rs.getString("contents"));
    // ...
    // files = new ArrayList<>();
    // board.setFiles(files);
    // boardNo = board.getNo();
    // }
    // AttachFile file = new AttachFile();
    // file.setNo(rs.getInt("board_file_id"));
    // file.setFilePath(rs.getString("file_path"));
    // file.setBoardNo(rs.getInt("board_id"));
    // files.add(file);
    // }

    sqlSession.close();
  }
}
  • BoardMapper.xml에 게시글과 첨부파일을 조회할 수 있는 select문이 하나 포함되어있다.
<?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="BoardMapper2">

  <resultMap type="Board" id="BoardMap">
    <id column="board_id" property="no"/>
    <!-- 
    <result column="title" property="title"/>
    -->
    <result column="contents"     property="content"/>
    <result column="created_date" property="registeredDate"/>
    <result column="view_count"   property="viewCount"/>
    
	  <collection property="files" ofType="AttachFile">
	    <id column="board_file_id" property="no"/>
	    <result column="file_path" property="filePath"/>
	    <result column="board_id"  property="boardNo"/>
	  </collection>
	  
  </resultMap>
  
  <select id="selectBoardWithFile" resultMap="BoardMap" parameterType="int">
    select 
      b.board_id,
      b.title, 
      b.contents, 
      b.created_date,
      b.view_count,
      f.board_file_id,
      f.file_path 
    from x_board b 
      left outer join x_board_file f on b.board_id=f.board_id
    where b.board_id = #{no}
  </select>
</mapper>

태그:

카테고리:

업데이트: