Spring BootでMySQLに接続する

Spring BootでMySQLに接続する

Spring BootでMySQLに接続してみます。

まずpom.xmlを変更します。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

次にMySQLに接続する情報を、src/main/resources/配下にapplication.propertiesというファイル名を作成し、以下情報を記述します。

spring.datasource.url=jdbc:mysql://ホスト名:3306/testdb
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

ホスト名は、localhostか他PCの場合、そのIPアドレスを指定します。今回はMySQLをインストールしているPCを別のPCにしています。

2019/01/09追記

com.mysql.jdbc.Driverは非推奨です

では、MySQLに接続してコンソールに結果を表示するプログラムです。

package com.mysql;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.JdbcTemplate;

@EnableAutoConfiguration
@ComponentScan
public class App{
  @Autowired
  private JdbcTemplate jdbc;

  public void method() {
    List<Map<String, Object>> list = jdbc.queryForList("SELECT * FROM TBL_CUSTOMER");
    list.forEach(System.out::println);
  }

  public static void main(String[] args) {
    try (ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args)) {
      App m = ctx.getBean(App.class);
      m.method();
    }
  }
}

プロジェクトを右クリックして、「実行」-「Spring boot app」で実行できます。

この時、以下のようなエラーが出る場合があるかもしれません。

Cannot determine embedded database driver class for database type NONE

この場合、ググって調べましたがpom.xmlに以下を追記するとエラーが解消されるとのことでした。

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <scope>test</scope>
</dependency>

それでもエラーが出た場合はとりあえず他PCのファイアウォールを無効にしてください。

これでコンソールにSQLの結果が表示されるはずです。

※MySQLのテーブルについては「MySQLのテーブル作成と存在確認」参照

普通に全件取得するSQLを記述しましたがプレースホルダを使用してSQLを作成することも可能です。

package com.mysql;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

@EnableAutoConfiguration
@ComponentScan
public class App{
    @Autowired
    private NamedParameterJdbcTemplate jdbc;

    public void method() {
        // プレースホルダ
        SqlParameterSource param = new MapSqlParameterSource().addValue("p",2);
        String name = jdbc.queryForObject("SELECT COUNT(*) FROM TBL_CUSTOMER WHERE ID=:p",param,String.class);
        
        System.out.println("count = " + name);
    }
    
    public static void main(String[] args) {
        try (ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args)) {
            App m = ctx.getBean(App.class);
            m.method();
        }
    }
}

JdbcTemplateをNamedParameterJdbcTemplateに変えています。

MapSqlParameterSource().addValue()の第一引数にプレースホルダ、第二引数に置換文字を指定するだけです。

上記は、カウントを取得するだけですが、idとfirst_nameを取得して表示したい場合があるとします。

その場合は、RowMapperを使用します。

package com.mysql;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import com.mysql.domain.Customer;

@EnableAutoConfiguration
@ComponentScan
public class App{
  @Autowired
  private NamedParameterJdbcTemplate jdbc;

  public void method() {
    // プレースホルダ
    SqlParameterSource param = new MapSqlParameterSource().addValue("p",1);
    // 匿名クラスにする
    Customer result = jdbc.queryForObject("SELECT ID , FIRSTNAME,LASTNAME FROM TBL_CUSTOMER WHERE ID=:p",param,
      new RowMapper<Customer>(){
        @Override
        public Customer mapRow(ResultSet rs,int rownum) throws SQLException{
          // コンストラクタ
          return new Customer(rs.getInt("ID"),rs.getString("FIRSTNAME"),rs.getString("LASTNAME"));
        }
      }
    );
    System.out.println("result = " + result);
  }

  public static void main(String[] args) {
    try (ConfigurableApplicationContext ctx = SpringApplication.run(App.class, args)) {
      App m = ctx.getBean(App.class);
      m.method();
    }
  }
}

結果は以下になります。

result = Customer(id=1, firstname=yamada, lastname=taro)

mysql-connector-java → mysql-connector-j

Note: This artifact was moved to:

com.mysql » mysql-connector-j

MySQL Connector/J artifacts moved to reverse-DNS compliant Maven 2+ coordinates.

コメント

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