snaag / TIL

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

22-12-05-MON #18

Open snaag opened 1 year ago

snaag commented 1 year ago
snaag commented 1 year ago

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

H2 데이터베이스 설치

H2란?

https://ko.wikipedia.org/wiki/H2_(DBMS)

H2 설치하고 실행하기

H2에 데이터베이스 파일 생성하기

스크린샷 2022-12-06 오전 12 49 37 스크린샷 2022-12-06 오전 12 49 49

H2 를 사용해서 테이블 만들고, 데이터 넣기

스크린샷 2022-12-06 오전 12 50 45
create table member
(
    id bigint generated by default as identity not null,
    name varchar(255),
    primary key(id)
)
insert into member (name) values ('name1');

테이블 관리하기

잘 안되는 경우

image
snaag commented 1 year ago

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

순수 JDBC

build.gradle 파일에 H2, JDBC 라이브러리 추가

implementation 'org.springframework.boot:spring-boot-starter-jdbc' // jdbc 드라이버
runtimeOnly 'com.h2database:h2' // db client

application.properties 에 스프링 부트 DB 연결 설정 추가

spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa

JdbcMemberRepository 구현 클래스 구현하기

image

https://github.com/snaag/study-hello-spring/blob/ab23af3f5ef8f81ba9d728cb788b07c3767a1401/src/main/java/hello/hellospring/repository/JdbcMemberRepository.java#L1-L179

SpringConfig 수정

스크린샷 2022-12-06 오전 2 04 50
@Configuration
public class SpringConfig {

    // +++++++++++++++
    private DataSource dataSource;

    @Autowired
    public SpringConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    // +++++++++++++++

    // spring bean 에 등록하라는 뜻
    @Bean
    public MemberService memberService() {
        return new MemberService(memberRepository());
    }

    @Bean
    public MemberRepository memberRepository() {
      // 주석 처리함
      // return new MemoryMemberRepository();
        return new JdbcMemberRepository(dataSource);
    }
}

구현체만 쉽게 갈아끼울 수 있는 스프링 (스프링의 장점)