【Spring】Description: 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 解決方法

SpringBootにおいてアプリケーション実行時、以下のようなエラーが出た際の解決方法を紹介します。

Description: 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

原因

データベースのドライバーを依存関係に追加しているが、その設定がされていないか、うまくいっていないことが原因です。

Gradleの場合、build.gradle、Mavenの場合、pom.xmlのdependenciesにMySQL,Oracle,PostgreSQLなどのドライバーがあり、かつJPA(JavaPersistenceAPI)があるときにこのようなエラーメッセージが表示されます。

一例:

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'org.postgresql:postgresql'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.springframework.security:spring-security-test'
}

解決方法

resourceディレクトリ下のapplication.propertiesに必要な情報を記述します。

あくまで例ですので、適時変更する必要があります。

例:Oracle

spring.datasource.url=jdbc:oracle:thin:@localhost:1521:testdb
spring.datasource.username={username} 
spring.datasource.password={password}
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

例:MySQL

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username={username}
spring.datasource.password={password}
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

例:PostgreSQL

spring.datasource.url=jdbc:postgresql://localhost:5432/testdb
spring.datasource.username={username}
spring.datasource.password={password}
spring.datasource.driverClassName=org.postgresql.Driver

1行目の数字は、ポート番号、testdbはデータベース名です。

2行目と3行目は、ユーザー名とパスワードです。データベースに登録したユーザー名とパスワードを入れてください。

4行目は、ドライバーのクラス名ですが、ここは、コピペで大丈夫です。

そして、再度アプリケーションを実行してみましょう。うまく動くはずです。