본문으로 바로가기

마이바티스 CRUD(수정)

category 데이터베이스/마이바티스 2019. 1. 7. 18:18

마이바티스 CRUD(수정)


이번에는 CRUD중 수정에 대해서 알아보도록 하겠습니다.


데이터를 수정하고자 할때 마이바티스는 어떻게 쓰이는가??


앞서 봤듯이 전통적인 JDBC 코드를 살펴봅시다.


public Integer updateComment(Comment comment) {

Connection conn = null;

PreparedStatement stmt = null;


try {

conn = this.getConnection();


StringBuilder sql = new StringBuilder("");

sql.append("UPDATE comment SET ");

sql.append(" comment_content = ? ");

sql.append("WHERE comment_no = ? ");

stmt = conn.prepareStatement(sql.toString());

stmt.setString(1, comment.getCommentContent());

stmt.setLong(2, comment.getCommentNo());

return stmt.executeUpdate();

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

stmt.close();

} catch (SQLException e) {

}

try {

conn.close();

} catch (SQLException e) {

}

}

return null;

}


빨간색 코드 부분은 데이터베이스 연결 생성 부분입니다. 앞서 조회 삽입을 설명할 때와 동일하므로 생략합

니다.


마찬가지로 SqlSession 객체 생성으로 변환 됩니다.(마이바티스)


초록색 코드 부분은 PreparedStatement 객체를 생성 부분으로 SQL구문을 생성합니다.


마이바티스 코드로 변환 시 매핑 구문을 정의합니다.


파란색 코드 부분은 PreparedStatement 객체에 파라미터 지정 후 실행 시키는 부분입니다.


이는 마이바티스에서 update 메소드 호출하는 부분입니다.


나머지 부분은 자원을 해체하는 부분으로 마이바티스에서 sqlSession 객체를 close()하는것과 동일합니다.



이제 매핑구문으로 분리를 해봅시다.


CommentMapper.xml에서 <update> 태그를 추가하여 위의 sql 문을 추가하면 됩니다.



<?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="ldg.mybatis.repository.mapper.CommentMapper">



<update id="updateComment" parameterType="ldg.mybatis.model.Comment">

UPDATE comment SET 

comment_content = #{commentContent}

WHERE comment_no = #{commentNo};

</update>


</mapper>


xml에 빨간색 부분만 추가해주면 됩니다. 즉 update 태그의 속성으로 id는 updateComment(나중에 쓰임) 


파라미터 타입은 Comment 마찬가지로 resultType은 생략 가능합나디ㅏ.



이제 마이바티스 코드를 생성해야합니다.



마찬가지로 SQL 실행 하고 자원 해체 일만 남았습니다.


우선 마이바티스 코드를 보시죠.


public Integer updateComment(Comment comment) {

SqlSession sqlSession = getSqlSessionFactory().openSession();

try {

String statement = "ldg.mybatis.repository.mapper.CommentMapper.updateComment";

int result = sqlSession.update(statement, comment);

if (result > 0) {

sqlSession.commit();

}

return result;

} finally {

sqlSession.close();

}

}


빨간색 코드 부분은 앞서 봤듯이 마이바티스 객체를 생성하는 부분입니다.


제일 중요한 부분이죠.


매핑구문을 호출하기 위해서는 위 객체가 필요합니다.


따라서 생성을 해줍니다.


이 작업은 전통적인 JDBC코드에서 데베로 연결 부분입니다.


주황색 코드 부분은 매퍼 구문의 id를 통해 위에서 만든 객체로 update 메소드를 호출 합니다. 이때 첫 파


라미터로 지정을 해줍니다.


이 작업은 executeUpdate를 호출하는 것이죠.


마지막으로 커밋 후 자원을 해체해 줍니다.(sqlSession.close())



이제 준비가 완료 됐으므로 이를 사용해야합니다.




public class CommentSessionRepositoryTest {

  public static void main(String[] args){

Long commentNo = 1L;

String commentContent = "수정 test";

    CommentSessionRepository commentSessionRepository = new     CommentSessionRepository();

//수정할 받아온 댓글 번호와 댓글 내용을 Comment에 넣고 이를 위 메소드 호출

Comment comment = new Comment();

comment.setCommentNo(commentNo);

comment.setCommentContent(commentContent);

Integer result = commentSessionRepository.updateComment(comment);


System.out.println(result);

}



}



마찬가지로 앞에 설명한것과 비슷하여 설명은 생략하나 아래서부터 위 방향으로 흐름을 파악하시면 편할 


거라고 생각됩니다.


즉 코드에서 commentSessionRepository 객체를 생성 후 이를 통해 수정을 위해 updateComment를 호출합니다. 


해당 호출된 코드로 가서(마이바티스 코드) 여기서 매퍼구문을 불러드리겠죠.


다음으로 삭제만 남았습니다. 삭제에 대해 포스팅 하겠습니다. 감사합니다.





'데이터베이스 > 마이바티스' 카테고리의 다른 글

마이바티스 활용  (0) 2019.01.23
마이바티스 CRUD(삭제)  (0) 2019.01.09
마이바티스 CRUD(삽입)  (0) 2019.01.04
마이바티스 CRUD(조회)  (0) 2019.01.03
마이바티스 CRUD(자바모델클래스)  (0) 2019.01.02