[Spring] 스프링 입문 - DB 접근 기술 : 스프링 JdbcTemplate

jy9922·2022년 8월 10일
0

Spring

목록 보기
9/34
post-thumbnail

스프링 JdbcTemplate

  • 순수 Jdbc와 동일한 환경설정
  • 스프링 JdbcTemplate과 MyBatis 같은 라이브러리는 JDBC API에서 본 반복 코드를 대부분 제거
  • SQL은 직접 작성

JdbcTemplateMemberRepository

/* JdbcTemplateMemberRepository */
public class JdbcTemplateMemberRepository implements MemberRepository {
	private final JdbcTemplate jdbcTemplate;
    
    // 생성자가 하나만 등록되면, @Autowired가 생략될 수 있음
    // Spring이 DataSource 자동 injection
    // @Autowired
    public JdbcTemplateMemberRepository(DataSource dataSource) {
    	jdbcTemplate = new JdbcTemplate(dataSource);
    }
    
	@Override
    public Member save(Member member) {
    	SimpleJdbcInsert jdbcInsert = new SimpleJdbcInsert(jdbcTemplate);
        jdbcInsert.withTableName("member").usingGeneratedKeyColumns("id");
        
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("name", member.getName());
        
        Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(parameters));
        member.setId(key.longValue());
        return member;
    }
    
    @Override
    public Optional<Member> findById(Long id) {
    	List<Member> result = jdbcTemplate.query("select * from member where id = ?", memberRowMapper(), id);
        return result.stream().findAny();
    }
    
    @Override
    public Optional<Member> findByName(String name) {
    	List<Member> result = jdbcTemplate.query("select * from member where name = ?", memberRowMapper(), name);
        return result.stream().findAny();
    }
    
    @Override
    public List<Member> findAll(){
    	return jdbcTemplate.query("select * from member, memberRowMapper());
    }
    
    private RowMapper<Member> memberRowMapper(){
    	return (rs, rowNum) -> {
            	Member member = new Member();
                member.setId(rs.getLong("id"));
                member.setName(rs.getString("name"));
                return member;
        };
    }
}   

SpringConfig

@Bean
public MemberRepository memberRepository(){
	return new JdbcTemplateMemberRepository(dataSource);
}

테스트 코드로 테스트 진행

0개의 댓글