[Spring] Spring Boot Application과 DB 연동

WOOK JONG KIM·2022년 10월 26일
0
post-thumbnail

우선 프로젝트 생성 시 SQL : Spring Data JPA와 MariaDB Driver 추가

이후 Swagger pom.xml에 의존성을 추가하였음

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
</dependency>
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
</dependency>

config 패키지에 SwaggerConfiguration 작성

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.jpa"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot Open API Test with Swagger")
                .description("설명 부분")
                .version("1.0.0")
                .build();
    }
}

Spring Data JPA에 의존성을 추가한 후에는 별도의 설정이 필요
-> 애플리케이션이 정상적으로 실행될 수 있게 연동할 데이터베이스의 정보를 application.properties에 작성해야함

spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/springboot
spring.datasrouce.username=root
spring.datasource.password = password

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

driverClassName에는 연동하려는 DB의 드라이버를 정의

마리아 DB의 경우 org.mariadb.jdbc.Driver 입력하고 pom.xml에도 mariadb-java-client 의존성이 필요

spring.datasource.url 항목에서는 마리아DB의 경로임을 명시하고 경로와 데이터베이스명 입력

밑에는 데이터베이스 설치시 설정한 계정정보 기입

윗 문단은 데이터베이스를 연동하는데 사용하는 값 설정

밑 문단은 하이버네이트를 사용할 때 활성화 할수 있는 선택 사항

  • ddl - auto : 데이터베이스를 자동으로 조작하는 옵션
  • create : 애플리케이션이 가동되고 SessionFactory가 실행될 때 기존 테이블을 지우고 새로 생성
  • create-drop : create와 동일한 기능을 수행하나 애플리케이션을 종료하는 시점에 테이블 지움
  • update : SessionFactory가 실행될 때 객체를 검사해서 변경된 스키마 갱신, 기존에 저장된 데이터는 유지
  • validate : update처럼 객체를 검사하지만 스키마는 안건들임, 검사 과정에서 데이터베이스의 테이블 정보와 객체의 정보가 다르면 에러 발생
  • none : ddl-auto 기능 사용 X

운영환경에서는 create,create-drop, update기능 사용X, 주로 validate,none 사용
-> DB에 축적된 데이터 지워버릴수도 있고, 사람의 실수로 정보가 변경 됐을 때 운영환경의 DB정보까지 변경될 수 있기 때문

개발환경에서는 create,update 사용하는 편

show-sql은 쿼리 문 출력
format_sql은 사람이 보기 좋게 포매팅

profile
Journey for Backend Developer

0개의 댓글