Portfolio/Spring Boot

스프링 부트 12일차 - CORS, 인메모리 DB(H2), DBCP, JdbcTemplate, Spring Data JPA

Foo 2019. 4. 18. 19:17
728x90

1. Origin은

  - URI 스키마(http, https)

  - hostname (naver.com, localhost, xx.xx.xx.xx)

  - Port(80, 443, 8080)


2. 스프링 부트에서 CORS를 지원해주기 위해서는 크게 2가지 방법이 있음.

Mapping이나 Controller에 걸고싶다면 @CrossOrigin(origins = "http://localhost:8080") 같은 식으로 작성 가능

만약 해당 애플리케이션 전체에 걸고싶다면 다음과 같이 @Configuration 작성

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry, registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080");
}
}


3. 스프링 부트에서 지원하는 인메모리 DB는

  H2, HSQL, Derby가 있음. 그중 H2 추천


4. 사용하려면 다음과 같은 의존성 추가

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


5. 스프링부트는 기본적으로 인메모리 DB를 사용함.

  기본 DB 접속은

  URL : "testdb"

  username: "sa"

  password: ""


이다.

다음과같이 properties를 설정하면 웹에서 /h2-console 로 접속 가능

spring.h2.console.enabled=true

JDBC URL이 ~를 사용해서 홈 디렉토리로 되어있을 텐데 그러면 안됨.

jdbc:h2:mem:testdb

로 바꿔주어야함.




6. 스프링 부트는 기본적으로 HikariCP를 DBCP(Connection Pool)로 사용


7. mysql 커넥터를 추가해주려면 다음과 같은 의존성 추가

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

넘 당연하게도 이건 mysql DB 자체를 실행시키는게 아니라 커넥터를 추가한거임. mysql 쓰려면 DB 설치해야함.

 * 아님 Docker로 깔거나


8. mysql을 사용할 경운 엔터프라이즈 환경에서는 오라클에 라이센스 비용 지불 + GPL 라이센스로 소스코드 공개 의무임

  mariaDB도 GPL 2.0으로 소스코드 공개는 마찬가지

  그래서 Oracle DB와 매우매우 유사하고 소스코드 공개할 필요 없는 PostgreSQL 사용 권장


9. datasource는 다음과 같이 application.properties에 사용

spring.datasource.url=jdbc:postgresql://localhost:5432/springboot
spring.datasource.username=이름
spring.datasource.password=비번


10. 어떤 DB를 사용하더라도 JdbcTemplate가 핵심임. 각종 DB 커넥터의 인터페이스가 됨. 다음과 같이 사용(예외, 리소스 정리 등등 잘 해줌 ㅎ)

@Autowired
JdbcTemplate jdbcTemplate
;

@Autowired
DataSource dataSource;

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.executeUpdate(sql);
}

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


11. JPA는 JAVA에서의 ORM의 표준이됨.

   Hibernate로부터 만들어졌음(Hibernate로부터 만들어졌다는 말에 조금 어폐가 있을 수도 있음. JPA는 명세이고, Hibernate는 JPA를 구현한 구현체임.)

 * 다음 링크 참고 https://suhwan.dev/2019/02/24/jpa-vs-hibernate-vs-spring-data-jpa/

요약하면 다음과 같이 요약가능

  - JPA는 기술명세

  - Hibernate는 JPA의 구현체

  - Spring Data JPA는 JPA를 쓰기 편하게 만들어놓은 모듈

위 링크 요약이고, 그림을 보면 더 쉽게 이해가 될 것임.