Spring Basic : H2 Database 신경 쓸 것들
1. 이 포스트는 스프링 내장 데이터베이스 H2를 사용할 때 주의할 점이다.
2. 프로그램을 재기동한다고 해서 무조건 저장된 데이터가 삭제가 되는 것이 아니다. 종종 안될 때도 있다.
2-1 제대로 삭제가 되지 않으면 mvn clean으로 프로그램을 완전 삭제하고 mvn spring-boot:run(리빌드)을 실행한다.
3. 주요 키워드가 있어서 사용하면 안되는 단어들이 있다. 예를 들면 order, createdat 같은 것이다.
3-1 order를 테이블 이름으로 사용하면 그냥 에러가 나버린다. 이유도 제대로 설명해주지 않고 에러가 뜬다.
3-2 createdAt를 속성으로 사용하면 created_at을 찾는다.
3-2-1 @Column(name="createdAt")이라고 해도 create_at을 찾는다.
4. 절대로 schema.sql과 jpa 자동테이블 생성을 같이 사용하면 안된다.
4-0 데이터 로딩용 data.sql은 사용할 수 있다.
4-1 schema.sql을 사용하는 경우는 반드시 applicaton.properties에서 아래처럼 자동생성을 막아야 한다.
spring.jpa.hibernate.ddl-auto=none
4-2 h2의 경우는 자동생성을 권장하는데 워낙 사용할 수 없는 키워드들이 많기 때문이다.
4-3 웬만하면 다른 데이터베이스를 사용하는 게 좋다.
5. 스프링 최신 버전의 경우는 기본 데이터베이스 이름이 random으로 생성되는 경우가 있다.
5-1 이럴 경우 데이터베이스 이름을 application.properties에 명시해주면 편리하다.
spring.datasource.url=jdbc:h2:mem:testdb
6. h2 데이터베이스의 console은 기본적으로 false 되어 있다. 그래서 그냥 볼수가 없다.
6-1 물론 spring devtools 의존성이 설정되어 있는 경우는 기본값이 true가 된다.
6-2 devtools을 사용하지 않는 경우는 아래처럼 명시적으로 enabled=true로 해주어야 console을 사용할 수 있다.
6-3 console의 접근 경로는 아래의 path 속성으로 변경할 수 있다.
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
7. 스프링 보안이 의존성에 추가된 경우에는 h2 console의 진입이 되지 않는다.
7-1 그럴 경우 보안설정에서 csrf를 해지하고 frameOptions를 disable 해야 진입이 가능하다.
package pe.pilseong.springdepth.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder((NoOpPasswordEncoder.getInstance()))
.withUser("pilseong").password("qwe123").roles("USER", "ADMIN").and()
.withUser("suel").password("qwe123").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and()
.authorizeRequests()
.antMatchers("/surveys/**").hasRole("USER")
.antMatchers("/users/**").hasRole("USER")
.antMatchers("/**").hasRole("ADMIN")
.anyRequest().authenticated().and()
.csrf().disable().headers().frameOptions().disable();
}
}