SpringのJdbcTemplateでOracleにSELECT発行してみた

スポンサーリンク
スポンサーリンク

SpringのJdbcTemplateでOracleにSELECT発行してみた

SpringのJdbcTemplateを使用してSELECTを実行してみます。

今回のプロジェクト構成は、以下になります。

この記事で使うバージョンは以下になります。

  • Windows 10 Home
  • Java11
  • Spring Tool Suite 4.6.2
  • Oracle 11gXE

JdbcTemplateSelectSampleApplication.java

Spring Starter Projectでプロジェクト作成した時に自動生成されるものです。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JdbcTemplateSelectSampleApplication {
  public static void main(String[] args) {
    SpringApplication.run(JdbcTemplateSelectSampleApplication.class, args);
  }
}

使用するテーブル

以下のテーブルとデータをOracleに作っておきましょう。

CREATE TABLE animal (animal_id CHAR(3),animal_name VARCHAR2(20));
insert into animal values ('001','いるか');
insert into animal values ('002','ぺんぎん');
insert into animal values ('003','うさぎ');
SQL> select animal_id,animal_name from animal;

ANIMAL_ID  ANIMAL_NAME
---------- ------------------
001        いるか
002        ぺんぎん
003        うさぎ

JdbcTemplateSelect.java

18~19行目でJdbcTemplateを使用するため依存性の注入をしています。

25行目でqueryForListメソッドを使用してSELECTを実行します。

28~33行目でSELECTして取得した結果をAnimalインスタンスに詰めなおします。

package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.demo.model.Animal;

@Controller
public class JdbcTemplateSelect {
  
  @Autowired
  JdbcTemplate jdbcTemplate;
  
  @GetMapping("/")
  public String selectAllAnimal(Model model) {
    String sqlText = "SELECT ANIMAL_ID,ANIMAL_NAME FROM ANIMAL";
    
    List<Map<String,Object>> resultList = jdbcTemplate.queryForList(sqlText);
    List<Animal> animalList = new ArrayList<Animal>();
    
    for(Map<String ,Object> result:resultList) {
      Animal animal = new Animal();
      animal.setAnimalId((String)result.get("animal_Id"));
      animal.setAnimalName((String)result.get("animal_name"));
      animalList.add(animal);
    }
    model.addAttribute("resultMessage","SELECT SUCCESS!!!");
    model.addAttribute("animalList",animalList);
    return "index";
  }
}

Animal.java

テーブル定義と同じカラムのフィールドを定義してゲッターセッターを用意します。画面側のindex.htmlで「th:each=”animal:${animalList}”」で定義して入力した値を取り出せるようにします。

package com.example.demo.model;

public class Animal {
  private String animalId;
  private String animalName;
  public String getAnimalId() {
    return animalId;
  }
  public void setAnimalId(String animalId) {
    this.animalId = animalId;
  }
  public String getAnimalName() {
    return animalName;
  }
  public void setAnimalName(String animalName) {
    this.animalName = animalName;
  }
}

Spring JdbcTemplateリファレンス

index.html

http://localhost:8888/にアクセスしてみてください。SELECTに成功したら画面に「SELECT Success!!!」が表示されてデータベースから取得した結果をテーブルに表示します。

<!DOCTYPE html>
<html xmlns="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="/css/style.css">
<title>JdbcTemplate SELECT Sample</title>
</head>
<body>
  <h1>SELECT sample</h1>  
  <p th:text="${resultMessage}"></p>
  <table border="1">
    <tr>
      <th>ID</th>
      <th>動物名</th>
    </tr>
    <tr th:each="animal:${animalList}">
      <td th:text="${animal.animalId}"></td>
      <td th:text="${animal.animalName}"></td>
    </tr>
  </table>
</body>
</html>

application.properties

ユーザネームとパスワードはご自身のを設定してください。ポートは空いてるものなら何でもいいです。自分の場合、デフォルトの8080を別アプリに割り当ててたので8888にしてます。

server.port=8888
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username={username}
spring.datasource.password={password}
spring.datasource.driverClassName=oracle.jdbc.OracleDriver

pom.xml

今回のプロジェクトのpomは、以下になります。

<?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.4.3</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>SpringTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>JdbcTemplateDDLSample</name>
  <description>Demo project for Spring Boot</description>
  <properties>
    <java.version>11</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jdbc</artifactId>
    </dependency>
    <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>com.oracle.database.jdbc</groupId>
      <artifactId>ojdbc8</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>

コメント

タイトルとURLをコピーしました