1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Boot × MySQL接続工程まとめ

Posted at

目次

  1. MySQL側の準備
  2. Spring Boot側の接続設定
  3. エンティティ(モデル)作成
  4. Respositoryインターフェース作成
  5. 動作確認とトラブル対策

フェーズ1MySQL側の準備

手順 内容
MySQLサーバーを起動しておく
接続用のデータベースを作成:例)create database mydb
必要なテーブルを作成:例)account,item,name etc....
テストデータを挿入:例)insert into account(user,passw) values ('test太朗','123456789')

フェーズ2Spring Boot側の接続設定

application.propeties(または.yml)に以下を記述

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=(ログインアカウント)
spring.datasource.password=あなたのパスワード
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

pom.xmlまたはbuild.gradleにMySQL JDBC ドライバを追加(Mavenの場合):

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

フェーズ3:エンティティ(モデル)作成

手順 内容
Account.java などを model/ に作成
テーブル名が自動推論と違う場合は @Table(name = "account") を明示
カラム名が違う場合は @Column(name = "...") を明示
必須アノテーション:@Entity, @Id, @GeneratedValue など

フェーズ4:Repositoryインタフェース作成

手順 内容
AccountRepository.javarepository/ に作成
JpaRepository<Account, Long> を継承
任意で Optional<Account> findByUsernameAndPassword(...) を定義

フェーズ5:動作確認とトラブル対策

手順 内容
Spring Boot を起動し、エラーが出ないか確認
Thunder Client や Postman で /login にテスト送信
エラーが出たら以下の順で確認:
✔ テーブル名が一致してるか?
✔ アノテーションが正しくついてるか?
✔ 接続URLが正しいか?
✔ MySQLが起動中か?

1️⃣ MySQL起動 & household DB用意
2️⃣ account テーブル作成 & INSERT
3️⃣ application.properties 設定確認
4️⃣ Entity (@Entity, @Table など) 作成
5️⃣ Repository (JpaRepository) 実装
6️⃣ 起動 & ThunderClient でPOST確認

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?