본문 바로가기
Spring

[SpringBoot] MySQL 연동

by ilyadelavie 2022. 9. 16.

1. 스트링부트 프로젝트 생성(gradle 빌드)

//기본 dependency
dependencies {
   implementation 'org.springframework.boot:spring-boot-starter'
   runtimeOnly 'mysql:mysql-connector-java'
   testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

 

2. 커넥션 정보 작성


h2 DB 사용 시 AutoConfigure에서 설정을 잡아주기 때문에 별도의 설정이 필요없으나 MySQL 사용 시에는 커넥션 정보를 별도로 작성해줘야 한다.

  • driver-class-name
    • com.mysql.jdbc.Driver와 com.mysql.cj.jdbc.Driver 두가지가 있으나 전자는 Deprecated이므로 com.mysql.cj.jdbc.Driver를 사용
  • url
    • localhost:3306/[DB 스키마]   
    • serverTimezone=UTC    ->    URL 쿼리 스트링에 serverTimezone을 작성해줘야 에러가 발생하지 않으므로 필수 작성
  • username/password
    • MySQL 계정 정보 확인하는 방법
      • 더보기
        mysql -uroot -p  : mysql root로 접속
        select user, host from user;  : user 조회

 

application.properties

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/example?serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=1234

 

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/example?serverTimezone=UTC&characterEncoding=UTF-8
    username: root
    password: 1234

 

※ 에러 발생 및 해결

프로젝트아래와 같은 에러 발생 시

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

 

'Spring' 카테고리의 다른 글

외부 API 장애 대응을 위한 Circuit Breaker 구현(Feat.함수형 프로그래밍)  (0) 2023.07.13
Mockito 사용하기  (1) 2022.09.14
Slice Test  (0) 2022.09.14