ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JDBC] JDBC 템플릿
    데이터베이스/JDBC 2024. 11. 6. 19:04

    JDBC 템플릿 선언

    public class Test{
    
        private final JdbcTemplate template;
    
        public Test(DataSource dataSource){
            template = new JdbcTemplate(dataSource);
        }
        
    }

     

    JDBC 템플릿 사용법

    • 삽입, 업데이트, 삭제
    template.update([sql구문], [구문에필요한 파라미터1], [구문에필요한 파라미터2] ..)
    • 조회
      • RowMapper는 결과값을 매핑하는 용도
    template.update([sql구문], [RowMapper()] , [구문에필요한 파라미터2] ..)
    private RowMapper<Member> testRowMapper() {
             return (rs, rowNum) -> {
                 Object obj = new Object();
                 obj.setxxx(rs.getString("결과조회1"));
                 obj.setxxx(rs.getInt("결과조회2"));
                 return object;
    }; }

     

    예제

    • Insert 구문은 결과값이 없어서 RowMapper() 필요없음
    • select 구문은 결과값이 있어 RowMapper 필요
      • .queryForObject()의 경우 Object를 반환함
    public class Repository{
    
        private final JdbcTemplate template;
    
        public Repository(DataSource dataSource){
            template = new JdbcTemplate(dataSource);
        }
        
        public Member save (Member member){
            template.update("insert into member(member_id, money) values(?,?)", member.getMemberId(), member.getMoney());
            return member;
        }
        
        public Member findById(String memberId){
            return template.queryForObject("select* from member where member_id = ?" , memberRowMapper(), memberId);
        }
        
        private RowMapper<Member> memberRowMapper() {
             return (rs, rowNum) -> {
                 Member member = new Member();
                 member.setMemberId(rs.getString("member_id"));
                 member.setMoney(rs.getInt("money"));
                 return member;
        }; }
    }

    '데이터베이스 > JDBC' 카테고리의 다른 글

    [JDBC] 스프링 예외 변환기  (0) 2024.11.06
    @Transactional  (0) 2024.11.06
    [JDBC] 트랜잭션 템플릿  (1) 2024.11.06
    [JDBC] 트랜잭션 매니저  (0) 2024.11.05
    [JDBC] 트랜잭션  (0) 2024.11.05
Designed by Tistory.