< 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 <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();
}
'SPRING' 카테고리의 다른 글
[Mybatis] DAO 구현 방법 2 (mapper interface / annotation) (0) | 2019.06.03 |
---|---|
DAO Support Class (0) | 2019.05.13 |
[SimpleJdbcInsert] (0) | 2019.05.13 |
[NamedParameterJdbcTemplate] (0) | 2019.05.13 |
[JdbcTemplate] 그 외 메소드 / 가변 길이 인자 지원 (0) | 2019.05.13 |