Study/spring

[Java] Spring Boot 3 MySQL 연동하기

 

Spring Boot 3에서 MySQL을 연동하는 방법에 대해 설명드리겠습니다.

 

의존성 추가

MySQL을 연동하기 위해 다음 의존성을 추가합니다.

Maven

<dependencies>    
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	<dependency>
		<groupId>com.mysql</groupId>
		<artifactId>mysql-connector-j</artifactId>
		<scope>runtime</scope>
	</dependency>
</dependencies>

 

Gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.mysql:mysql-connector-j'
}

 

 

 

 

DB 연결 정보 추가

Spring Boot에 설정 정보를 추가합니다.

 

프로젝트를 생성하면 src > main > resources에 application.properties 파일이 생깁니다.

여기다가 정보를 추가해도 되고, application.properties 파일을 application.yml 파일로 바꿔서 사용해도 됩니다.

application.properties

spring.datasource.url=jdbc:mysql://<데이터베이스 주소>:<포트>/<연결할 데이터베이스>
spring.datasource.username=<데이터베이스 계정>
spring.datasource.password=<데이터베이스 비밀번호>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

 

application.yml

spring:
  datasource:
    url: jdbc:mysql://<데이터베이스 주소>:<포트>/<연결할 데이터베이스>
    username: <데이터베이스 계정>
    password: <데이터베이스 비밀번호>
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update

 

spring.datasource.url : 데이터베이스 주소 정보입니다. 데이터베이스 주소와 데이터베이스이름을 입력합니다.

spring.datasource.username: 데이터베이스 접속 계정입니다.

spring.database.password: 데이터베이스 접속 비밀번호입니다.

spring.datasource.driver-class-name: 사용할 Driver를 지정합니다.

spring.jpa.hibernate.ddl-auto: DDL 자동 생성 설정입니다.

 

연결 확인

의존성을 추가하고 데이터베이스 연결 정보를 추가하고 프로젝트를 시작하면 연결이 된 것을 확인할 수 있습니다.

Spring Boot MySQL 연결 성공 로그
Spring Boot MySQL 연결 성공 로그

 

만약에 데이터베이스 연결 정보가 잘못되어서 연결이 실패하면 다음과 같은 로그가 나옵니다.

Spring Boot MySQL 연결 실패 로그
Spring Boot MySQL 연결 실패 로그

잘못된 비밀번호를 설정했을 때 나오는 에러입니다.

비번이 틀리지 않았는데 위와 같은 에러가 나온다면 다른 설정 값이 잘못되었다는 의미입니다.

 

 

읽으면 좋은 글

[Java] Spring Boot 3 MySQL JPA 연동하기

 

[Java] Spring Boot 3 MySQL JPA 연동하기

Spring Boot 3에서 JPA를 연동하는 방법을 설명드리겠습니다. 연동 준비 데이터베이스 생성 프로젝트에서 사용할 데이터베이스를 생성합니다. spring_boot라는 데이터베이스를 생성하였습니다. 의존성

priming.tistory.com