Spring Bootでデータベース(SQL Server)にアクセスする方法
Spring Bootでデータベース(SQL Server)にアクセスする方法をご紹介します。
条件
- Spring Boot 2.1.4
- SQL Server 2019 Express Edition
- Spring Data JPA
- maven
- Microsoft SQL Server Management Studio
事前準備1
データベース作成
まずは、SQL Serverにデータベースおよびテーブルを作成します。
Microsoft SQL Server Management Studioでサーバーに接続後、以下を選択します。
オブジェクトエクスプローラー > データベース > 新しいデータベース
任意のデータベース名を入力してOKボタンを押します。
(ここでは「testdb」としました。)
テーブル作成
メニューバーの新しいクエリボタンを押して、クエリ画面を開きます。
例として以下のようなテーブルを作成します。
create table weather (
    id              int NOT NULL IDENTITY (1, 1)   primary key,   -- ID
    name            varchar(20),                                  -- 地名
    temperature     int,                                          -- 気温
    humidity        int,                                          -- 湿度
);
データ追加
テーブルにデータを追加します。
insert into weather (name, temperature, humidity) values 
   ('稚内', 1, 55),
   ('盛岡', 6, 53),
   ('前橋', 10, 40),
   ('名古屋', 12, 65),
   ('佐賀', 14, 67),
   ('那覇', 22, 69);
事前準備2
SQL Server認証モード
Microsoft SQL Server Management Studioで「SQL Server認証モード」を使用可能にします。
ログインユーザーについてパスワードの設定も行います。
詳細な手順は割愛しますが、以下のサイトを参考にさせて頂きました。
事前準備3
Sql ServerのTCP/IPの設定
Sql Server Configuration Managerで以下を設定/確認します。
(C:\Windows\System32 のSQLServerManager15.mscをダブルクリックで起動できます。)
- SQLEXPRESSのプロトコルでTCP/IPを「有効」にする。
- TCP/IPのプロパティ > IPアドレス > IPALL > TCP動的ポートのポート番号を確認する。(DB接続設定で使用します)
※TCP/IPを有効に設定変更した場合、Microsoft SQL Server Management StudioでSQLサーバーのサービスを再起動するのを忘れずに。
プロジェクト作成
プロジェクト構成
今回は以下のような構成としました。
DB接続情報の設定
「application.properties」に以下のような記述を追記します。(環境に応じて適宜変更してください。)
localhostの後のポート番号は、先ほど確認したTCP動的ポートのポート番号を設定します。
application.properties
spring.datasource.url=jdbc:sqlserver://localhost:51792;databaseName=testdb spring.datasource.username=sa spring.datasource.password=password
依存関係
「pom.xml」に以下の記述を追記します。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <scope>runtime</scope>
</dependency>
今回は以下のようになりました。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.2</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>helloSqlServer</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>helloSqlServer</name>
  <description>Example Project</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <scope>runtime</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
モデル
以下の通りとします。
Weather.java
package com.example.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "weather")
public class Weather {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private Integer temperature;
    private Integer humidity;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getTemperature() {
        return temperature;
    }
    public void setTemperature(Integer temperature) {
        this.temperature = temperature;
    }
    public Integer getHumidity() {
        return humidity;
    }
    public void setHumidity(Integer humidity) {
        this.humidity = humidity;
    }
}
リポジトリ
以下の通りとします。
WeatherRepository.java
package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.model.Weather;
@Repository
public interface WeatherRepository extends JpaRepository<Weather, Integer> {
}
サービス
以下の通りとします。
WeatherService.java
package com.example.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Weather;
import com.example.repository.WeatherRepository;
@Service
public class WeatherService {
    @Autowired
    WeatherRepository weatherRepository;
    /**
     * レコードを全件取得する。
     * 
     * @return
     */
    public List<Weather> findAllWeatherData() {
        return weatherRepository.findAll();
    }
}
コントローラ
以下の通りとします。
HelloSqlServerController.java
package com.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.model.Weather;
import com.example.services.WeatherService;
@Controller
public class HelloSqlServerController {
    @Autowired
    WeatherService weatherService;
    @RequestMapping("/")
    public String hello(Model model) {
        model.addAttribute("title", "SQL Serverから取得したデータ");
        // 気象データの取得
        List<Weather> weatherDataList = weatherService.findAllWeatherData();
        model.addAttribute("weatherDataList", weatherDataList);
        return "index";
    }
}
テンプレート
以下の通りとします。
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8" />
  <title></title>
</head>
<body>
<p>
  <span th:text="${title}">Hello World!</span>
</p>
<table>
  <tr th:each="data : ${weatherDataList}" th:object="${data}">
    <td th:text="*{id}"></td>
    <td th:text="*{name}"></td>
    <td th:text="*{temperature}"></td>
    <td th:text="*{humidity}"></td>
  </tr>
</table>
  
</body>
</html>
実行結果
プロジェクトを右クリック > 実行 > Spring Bootアプリケーション で実行します。
ブラウザで以下のURLを開きます。
以下のように、SQL Serverからデータを読み込んで表示できることがわかります。
参考
Microsoft:SQL Serverダウンロード
https://www.microsoft.com/ja-jp/sql-server/sql-server-downloads
Code Java:Spring Boot Connect to Microsoft SQL Server Examples
https://www.codejava.net/frameworks/spring-boot/connect-to-microsoft-sql-server-examples
JavaからSQL Serverに接続する
http://www.ria-lab.com/archives/1218









