LoginSignup
8
7

More than 5 years have passed since last update.

◆ Spring Boot+MyBatis+PostgreSQL DB接続①

Last updated at Posted at 2019-04-18

★ はじめに

引き続きSpringBootの学習記録、今回はDB接続に挑戦します。
ふだんoracleしか使わないのでまずPostgreSQLのインストールに手間取ってしまいました。

★ 取得内容

data01スキーマに名前や年齢などを保持するpersonテーブルを作成しました。
詳細な定義内容は以下になります。

personテーブル

Name Data Type Length NotNull PK
id integer -
name Character varying 30 - -
age integer - - -
hobby Character varying 300 - -

データ

テーブルの中身はこんな感じでデータを用意。

postgres=# select * from data01.person;
 id |  name  | age |  hobby
----+--------+-----+----------
  1 | ほげお |  20 | 鉱物集め
(1 )

★ 実装内容

build.gradle

mybatis、postgresqlを使用するために、build.gradleに以下を追加。

build.gradle
dependencies {
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.1'
    runtimeOnly 'org.postgresql:postgresql'
}

application.properties

application.propertiesにDB接続情報を記載。

application.properties
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres

Person.java

Person.java
package com.example.sample.domain.entity;

public class Person {

    /** ID */
    private Integer id;

    /** 名前 */
    private String name;

    /** 年齢 */
    private Integer age;

    /** 趣味  */
    private String hobby;

    // ★getter・setterは割愛

PersonMapper.java

mapperインタフェース。今回はxmlファイルにSQLを書かずに取得する方法をとります。

PersonMapper.java
package com.example.sample.domain.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.example.sample.domain.entity.Person;

@Mapper
public interface PersonMapper {

    @Select("SELECT * FROM data01.person ORDER BY id")
    public List<Person> findAll();

    @Select("SELECT * FROM data01.person WHERE id = #{id}")
    public Person findById(@Param("id") Integer id);

}

PersonService.java

ServiceクラスにはパラメータのIDより一意となるレコードを取得するメソッド、すべてのレコードを取得するメソッドを実装。

PersonService.java
package com.example.sample.app.domain.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.sample.domain.entity.Person;
import com.example.sample.domain.mapper.PersonMapper;

@Service
@Transactional
public class PersonService {

    @Autowired
    PersonMapper personMapper;

    public Person findById (Integer id) {
        Person person = personMapper.findById(id);
        return person;
    }

    public List<Person> findAll(){
        List<Person> personList = personMapper.findAll();
        return personList;
    }

}

RestApiController.java

URLパラメータよりIDを取得し、Seviceクラスに実装したfindByIdメソッドをコールし、取得結果を返却。

RestApiController.java
package com.example.sample.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.sample.app.domain.service.PersonService;
import com.example.sample.domain.entity.Person;

@RestController
@RequestMapping("api/sample")
public class RestApiController {

    @Autowired
    PersonService personService;

    @RequestMapping(value = "/getPerson/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Person getPerson(@RequestBody @PathVariable("id") Integer id) {
        Person person = personService.findById(id);
        return person;
    }
}

★ 実行結果

キャプチャ2.PNG

★ おわりに

業務で3年間ほどiBATISを利用していたので、やっぱりxmlファイルにSQL書きたい感。
②として後編記事作成します。

8
7
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
8
7