rainsister
  • 신비한 비 Blog
  • Design Pattern
    • Adapter Pattern
    • Proxy Pattern
    • Mediator Pattern
    • Visitor Pattern
    • State Pattern
    • Memento Pattern
    • Factory Pattern
    • Template Pattern
    • Strategy Pattern
    • Bridge Pattern
  • springboot 2.x
    • 메시징 - 큐
      • RabbitMQ 기본설정
      • RabbitMQ 지연 큐(delayed queue)
    • Log
      • 기본 Log 설정 및 Logback 설정
      • Log4j2 사용해보기
      • tinylog 모듈 사용해보기
    • 기타 Database 에 대한 기본가이드
      • PostgreSQL
      • InfluxDB
      • MongoDB
    • 수행속도 UP! 각종 cache 어노테이션 사용법
      • Redis를 사용하여 Cache 관리하기
      • EhCache 사용해보기
      • Thread내캐쉬사용 및 Cache 어노테이션 사용법
    • Database Connection
      • Springboot 2.5 이후 data init script 초기화에 대한 변경
      • JTA 로 JPA 다중 DataSource 트랜잭션 처리 하기
      • Flyway 로 DataBase 형상 관리해보자
      • 트랜잭션 기초읽기
      • MyBatis 의 다중 DataSource
      • Spring Data JPA 다중 DataSource
      • JdbcTemplate 다중 DataSource
      • XML 로 Mybatis 설정하기
      • Mybatis 로 Mysql 연결하기
      • ORM(Spring data jpa)
      • Druid datasource 연결
      • Hikari 설정
      • JdbcTemplate 로 db 접근
    • rest api
      • XML에 대한 요청 및 응답 처리
      • SpringFox 3 및 Swagger 설정
      • 프로젝트 구동 시 RequestMappingHandler 로그 설정
      • Swagger 의 api들을 분류하는 법
      • 간단한 Restful API 만들고 테스트 코드 작성
      • Swagger2 구성하여 API 문서 자동화하기
      • JSR-303 그리고 validation
    • 설정
      • 시작
      • 멀티환경구성에 대한 새로운 방법
      • 멀티환경구성에 대한 새로운 include
      • 프로젝트 설정파일
      • 민감한 정보에 대한 암호화
  • java버전별차이
    • JAVA18
    • JAVA9
    • JAVA10
    • JAVA11
    • JAVA14
    • JAVA15
    • JAVA17
    • JAVA16
  • spring노하우
    • BeanUtils 권장하지 않는이유
    • 개인정보 암호화
    • Springboot 3가지 CROS 설정
    • Springboot 내장된 유용한 Utils
    • Spring Security WebSecurityConfigurerAdapter 가 deprecated 된 이슈해결하기
    • 아직도 HttpUtil ? SpringBoot 3.0의 HTTP Client Util 을 사용해보라
    • JDBC 소스를 뽀개기
    • spring-boot-configuration-processor 는 뭐하는놈임?
    • Apache BeanUtils vs Spring BeanUtils 성능비교
  • Effetive Java 3th
    • Finalizer & Cleaner
Powered by GitBook
On this page
  1. springboot 2.x
  2. Database Connection

Springboot 2.5 이후 data init script 초기화에 대한 변경

아래 소스 코드를 관찰해 보자

위치는 : org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 이다

/**
 * Mode to apply when determining if DataSource initialization should be performed
 * using the available DDL and DML scripts.
 */
@Deprecated
private DataSourceInitializationMode initializationMode = DataSourceInitializationMode.EMBEDDED;

/**
 * Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or
 * data-${platform}.sql).
 */
@Deprecated
private String platform = "all";

/**
 * Schema (DDL) script resource references.
 */
private List<String> schema;

/**
 * Username of the database to execute DDL scripts (if different).
 */
@Deprecated
private String schemaUsername;

/**
 * Password of the database to execute DDL scripts (if different).
 */
@Deprecated
private String schemaPassword;

/**
 * Data (DML) script resource references.
 */
@Deprecated
private List<String> data;

/**
 * Username of the database to execute DML scripts (if different).
 */
@Deprecated
private String dataUsername;

/**
 * Password of the database to execute DML scripts (if different).
 */
@Deprecated
private String dataPassword;

/**
 * Whether to stop if an error occurs while initializing the database.
 */
@Deprecated
private boolean continueOnError = false;

/**
 * Statement separator in SQL initialization scripts.
 */
@Deprecated
private String separator = ";";

/**
 * SQL scripts encoding.
 */
@Deprecated
private Charset sqlScriptEncoding;

기존것(2.5 이전 버전)

spring.datasource.schema=
spring.datasource.schema-username=
spring.datasource.schema-password=
##...
##생략 

새로운 설정 방법 (2.5 이후 버전)

확인 해보니 org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties 클래스를 적용하였더라. 그래서 설정도 바뀐거다.

pom.xml 에 mysql 디펜던시를 추가한다.

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

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

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Spring Boot 2.5.0 init schema & data
# init script 이름
spring.sql.init.username=root
# init script 수행 user password 
spring.sql.init.password=
# init script 위치 
spring.sql.init.schema-locations=classpath*:schema-all.sqlr

resource 폴더에 schema-all.sql 생성

create table test.user_info
(
    id          int unsigned auto_increment comment 'user id'
        primary key,
    open_id     varchar(255)     default '' null comment 'openid',
    nick_name   varchar(255)     default '' null comment '닉네임',
    head_img    varchar(255)     default '' null comment '프로핀사진',
    sex         varchar(255)     default '' null comment '성별',
    phone       varchar(255)     default '' null comment '핸드폰',
    province    varchar(255)     default '' null comment '지역',
    city        varchar(255)     default '' null comment '도시',
    country     varchar(255)     default '' null comment '구/동',
    status      tinyint unsigned default 0  not null comment '삭제여부  0:아니 1:예',
    create_time datetime                    not null comment '생성시간',
    update_time datetime                    not null comment '수성시간'
)
comment '사용자 테이블';

설정후 springboot 구동하면Database에 jpa를 통하여 생성 된 기본 테이블 및 데이터가 생성된걸 확인 할수 있다.

spring.sql.init.enabled : 데이터를 초기화 할 것인지 선택 기본 true , false 를 선택하여 disable 상태로 만들어 놓는다. -D 명령어 사용 가능.

spring.sql.init.username和spring.sql.init.password : 스크립트 수행 사용자와 패스워드 . 해당 설정은 중요하다. 보안에서 db 계정마다 권한이 다르므로 해당 설정을 꼭 해줘야 생성, 삭제 명령 등 위험한 명령어 및 스크립트를 수행하는걸 방지한다.

spring.sql.init.schema-locations : schema 변경 관련 sql 스크립트, 다중 설정가능 기본값은 ; 임. spring.sql.init.data-locations : data 관련 스크립트설정, 다중설정가능 , 기본값은 ; 임. spring.sql.init.encoding:스크립트 인코딩

spring.sql.init.separator : 다중 설정 .sql 파일명 구분자 기본 값 ; 임

spring.sql.init.continue-on-error : 스크립트 실행 중 오류발생시 계속 진행할것인지 결정하는 값.기본값은 false.

PreviousDatabase ConnectionNextJTA 로 JPA 다중 DataSource 트랜잭션 처리 하기

Last updated 8 months ago