snaag / TIL

https://github.com/snaag/todo3/issues
3 stars 0 forks source link

22-12-06-TUE #19

Open snaag opened 1 year ago

snaag commented 1 year ago
snaag commented 1 year ago

스프링 입문 > 스프링 DB 접근 기술

스프링 통합 테스트

스프링 통합 테스트란?

코드

https://github.com/snaag/study-hello-spring/blob/9d5a1887b106fa2bfadbd52e790ce06145f23eac/src/test/java/hello/hellospring/service/MemberServiceIntegrationTest.java

@SpringBootTest
@Transactional
snaag commented 1 year ago

스프링 입문 강의 > 스프링 DB 접근 기술

스프링 JdbcTemplate

package hello.hellospring.repository;

import hello.hellospring.domain.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class JdbcTemplateMemberRepository implements MemberRepository {

    // injection 못받음, dataSource 필요
    private final JdbcTemplate jdbcTemplate;

    // 생성자가 하나라면, Spring bean 으로 등록된 경우, @Autowired 는 생략 가능
    @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) {
        // 결과를 RowMapper 라는 걸로 mapping 해야 함 ------- (A)
        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;
        };
    }
}

https://github.com/snaag/study-hello-spring/blob/050fc94dc9c9372ca39dd08aee38889a2bb92ed1/src/main/java/hello/hellospring/repository/JdbcTemplateMemberRepository.java