3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SpringBoot入門その2

Last updated at Posted at 2020-06-11

(注、この記事は書き途中です。後日更新します。)

SpringBoot入門その1を書いてから、1年以上経ってしまった(大汗)ということで、今回は1年ぶりのSpringBoot入門その2です。

今回は、Spring Data JPAによるデータベースへのアクセスとSpring Securityによる認証・認可について簡単に紹介したいと思います。

Spring Data JPAによるデータベースへのアクセス

  1. そもそもJPAとは何か

一言でいうと、Javaでの標準のO/Rマッパーです。O/Rマッパーは、ObjectとRelationを対応づける、すなわちオブジェクト指向のクラスとデータベースのテーブルを関連させるものと考えておけばいいでしょう。

例として、「顧客」というクラスがあるとします。メンバー変数としてはID(Integer、必須)、名前(String、必須)、性別(Byte、1:男 2:女)、年齢(Integer)を持っているとします。

この時、対応するcustomorテーブルはこんな感じになるでしょう。

id name gender age
1 鈴木 1 28
2 佐藤 2 30
3 田中 1
4 山田 26

Javaの顧客クラスからDBのcustomorテーブルに簡単にアクセスできるようにする仕組みが、JPAです。JPAには、このマッピングの他にもDBへのCRUD(Create,Read,Update,Delete)処理をカプセル化したAPIおよびJavaオブジェクトを間作するためのクエリ言語(JPQL)を持っています。

  1. pom.xmlとapplication.propertiesの設定

まずは、pom.xmlに、下記の内容を追加して、「spring-boot-starter-data-jpa」を読み込ませます。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

次に、application.propertiesに下記の設定をします。なお、ここではMySQLを使う場合を想定しています。

spring.datasource.url=jdbc:mysql://localhost:3306/database
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database=MYSQL
logging.level.jdbc=OFF
spring.jpa.hibernate.ddl-auto=validate
  1. エンティティとリポジトリの作成

次に、エンティティクラスとリポジトリインタフェースを定義します。
エンティティクラスは、いわゆるMVCの"M"にあたるもので、以下のように定義します。

@Entity
@Table(name = "customers")
public class Customer {
    @Id
    @GeneratedValue
    private Integer id;
    private String firstName;
    private String lastName;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(nullable = true, name = "username")
    private User user;
}

リポジトリインタフェースはJavaからデータベースにアクセスするためのインタフェースで、次のようにします。

import com.example.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface CustomerRepository extends JpaRepository<Customer, Integer> {
    @Query("SELECT x FROM Customer x ORDER BY x.firstName, x.lastName")
    List<Customer> findAllOrderByName();¥
}

最低限必要なのはエンティティクラスと"org.springframework.data.jpa.repository.JpaRepository"のインポートです。これに"org.springframework.data.jpa.repository.Query"を追加でインポートすることでSQL文を作ってそれを呼び出すメソッドの定義もできるようになります。

それ以外だと、Serviceクラスを作ってそこからエンティティへの操作を定義して、それをコントローラーから呼び出すという使い方をすることが多いです。
Serviceクラスの作り方、使い方については「SpringBoot入門その3」あたりで紹介しようと思います(いつになるかわからないけど)。

Spring Securityによる認証・認可

次に、セキュリティを保持するためのフレームワークである「Spring Security」を使って、Userクラスのaccountとpasswordによるログイン機能を作ることを考えてみます。

  1. pom.xmlの設定

まずは、pom.xmlに、下記の内容を追加して、「spring-security」を読み込ませます。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. application.propertiesの設定

今回はBASIC認証は使わないので、下記の設定でBASIC認証を無効にします(もちろん、有効にする場合はtrueにする)。

security.basic.enabled=false
  1. Userのエンティティとリポジトリの作成

「Spring Data JPAによるデータベースへのアクセス」で説明したやり方で、ログインユーザーを定義するユーザーのエンティティとリポジトリを作成します。

  1. SecurityConfigクラスの作成

詳細は後日記載しますが、org.springframework.security,config.annotation.web.configuration.EnableWebSecurityをインポートして@EnableWebSecurityをアノテーションにつけます。また、org.springframework.security,config.annotation.web.configuration.WebSecurityConfigurerAdapterをインポートしてWebSecurityConfigurerAdapterを拡張したSecurityConfigクラスを作成します。

こうして作成したSecurityConfigクラスにセキュリティ関連の設定を行なっていきます。ログインの永続化やCSRF対策の設定もここで行います。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?