Programming/Spring Boot

스프링 데이터 - 1 (스프링 부트 활용 - 7)

흠냐아뤼 2020. 3. 11. 15:50
728x90

 

1. 인-메모리 데이터베이스

- H2(추천 : 콘솔 때문에), HSQL, Derby

- 기본 연결 정보 (URL : "testdb", username: "sa", password : "")

 

1) H2, JDBC 를 의존성에 추가

 

2) Runner 코드를 작성

Spring-JDBC가 클래스 패스에 있으면 자동 설정이 필요한 빈(DataSource, JdbcTemplate)들을 설정해줌

@Component
public class H2Runner implements ApplicationRunner {

    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try(Connection connection = dataSource.getConnection();){
            System.out.println(connection.getMetaData().getURL());
            System.out.println(connection.getMetaData().getUserName());

            Statement statement = connection.createStatement();
            String sql = "CREATE TABLE USER(ID INTEGER NOT NULL," +
                    "NAME VARCHAR(255)," +
                    "PRIMARY KEY (ID))";
            statement.execute(sql);
        }

        jdbcTemplate.execute("INSERT INTO USER VALUES (1, 'hongchan')");
    }
}

 

2) H2 콘솔 사용하는 방법

- 외부 설정에 spring.h2.console.enabled=true 추가

- localhost:8080/h2-console 접속

 

연결 시험 후 연결

필자의 경우 JDBC URL이 맞지 않아 연결이 잘 되지 않아,

System.out.println(connection.getMetaData().getURL());

출력 값을 복붙하였다.

 

 

테이블 확인 및 데이터 확인

 

 

 

2. MySQL 설정하기

 

DBCP

- DBCP 란?  (DB Connection Pool) DB 커넥션을 관리함.

- 지원하는 DBCP Hikari CP (기본), Tomcat CP...

- auto commit, pool size와 같은 설정을 할 수 있음

 

1) MySQL 커넥터 의존성 추가

2) MySQL용 Datasource 설정

만약 이게 없으면 인 메모리 데이터베이스로 작동함

spring.datasource.url = jdbc:mysql://localhost:3306/springboot?useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = verylonglongpassworD!

3) Runner 작성

@Component
public class MySQLRunner implements ApplicationRunner {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String sqlCreate = "CREATE TABLE USER(ID INTEGER NOT NULL," +
                "NAME VARCHAR(255)," +
                "PRIMARY KEY(ID))";
        String sqlInsert = "INSERT INTO USER VALUES (1, 'hongchan')";
        jdbcTemplate.execute(sqlCreate);
        jdbcTemplate.execute(sqlInsert);
    }
}

 

 

MySql -> 상용으로 사용할 경우 라이선스 비용 + 소스코드 공개 의무 있음

MariaDB -> 소스코드 공개 의무 있음

PostgreSQL -> 의무x

 

 

2. PostgrSQL 설정하기

 

- docker 실행

docker run -p 5432:5432 -e POSTGRES_PASSWORD=pass -e POSTGRES_USER=hongchan -e POSTGRES_DB=springboot --name postgres_boot -d postgres

 

- 컨테이너 인터렉티브 bash 실행

docker exec -i -t postgres_boot bash

 

- 사용할 데이터 베이스 이름으로 접근

su - postgres
psql -U hongchan springboot

 

1) postgre 의존성 추가

2) 설정 변경

spring.datasource.url = jdbc:postgresql://localhost:5432/springboot?useSSL=false&serverTimezone=UTC
spring.datasource.username = hongchan
spring.datasource.password = pass

3) MySQL와 똑같은 코드로 실행

4) 테이블 확인

\l, \list
\dt

 

 

 

 

인프런 백기선님 '스프링 부트’ 강의를 듣고 정리한 내용입니다.
728x90