SPRING

[Mybatis] Dao 구현 방법 1 (mapper.xml / DAO class)

nang. 2019. 6. 3. 19:49
반응형
SMALL

< XML 방식 >

<mapper.xml>

1
2
3
4
5
6
7
8
9
<sql id="entity">
    comment_no as commentNo, user_id as userId, comment_content as commentContent, reg_date as regDate
</sql>
 
<select id="selectById" parameterType="long" resultType="com.example.model.Comment">
    select <include refid="entity"/>
    from Commnets
    where comment_no = #{commentNo}
</select>
 

* sql = 엔티티 같은 것

 

이걸 JDBC 기반의 DAO 구현으로 바꾸면?

 

public Comment selectById(long commentNo) {

    Connection conn = null;

    PreparedStatement stmt = null;

    ResultSet rs = null;

    String sql = "select comment_no, user_id, comment_content, reg_date" + "from Comments where comment_no = ?");

 

    try {

            conn = this.getConnection(); // Connection 생성

            stmt = conn.getPrepareStatement(sql); // PreparedStatement  생성

            stmt.setLong(1, commentNo); // 쿼리의 파라미터 값 설정

            rs = stmt.executeQuery(); // 질의 실행

            

            if(rs.next()) {

                Comment commnet = new Comment();

                comment.setCommentNo(rs.getLong("comment_no"));

                comment.setUserId(rs.getString("user_id"));

                comment.setCommentContent(rs.getString("comment_content"));

                comment.setRegDate(rs.getDate(rs.getDate("reg_date"));

                return comment;

            }

        }

}

 

 

 

 

 

<DAO class>

 

private SqlSessionFactory sqlSessionFactory = createSqlSessionFactory();

private SqlSessionFactory createSqlSessionFactory() {

     return new SqlSessionFactoryBuilder().build(inputStream);

}

 

public Comment selectById(Long commentNo) {

     SqlSession sqlSession = sqlSessionFactory.openSession();

 

     // select 이면!

     try { 

          return (Comment) sqlSession.selectOne(namespace + ".selectById", commentNo);

     } finally { 

          sqlSession.close();

     }

 

     // insert / update / delete 이면!

     try { 

          int result = sqlSession.insert(namespace + ".selectById", commentNo);

          if(result > 0) {

               sqlSession.commit();

          }

          return result;

     } finally { 

          sqlSession.close();

     }

 

 

반응형
LIST