以前の記事 Java から ORACLE DB へ接続してみる(調査偏) からの続きです。
今回は「Java から ORACLE DB へ接続してみる(実践偏)」ということで、実際に ORACLE DB に接続してデータを取得してみます。
データ取得には Spring Boot Data JPA を利用します。Spring Boot Data JPA は、効率的に DB のデータを扱うことの出来る便利なフレームワークです。便利なフレームワークは、定時で帰るためには積極的に取り入れたいものです。
Controller
まずフロント部分を作成します。
package com.example.app.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping(value = "/") public String simpleGet() { return "Hello HttpRequest GET"; } }
ブラウザでチェックして、Hello HttpRequest GET と表示されればOKです。
Entity
次に、DB のテーブルとマッピングさせる Entityクラス を作成します。
package com.example.app.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import lombok.Data; @Entity @Data public class SampleEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private String addres; }
Repository
Entity を引っ張ってくる Repository を作成します。Class でなく Interface なのがポイントです。
package com.example.app.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.app.entity.SampleEntity; @Repository public interface SampleRepository extends JpaRepository<SampleEntity, Integer> { }
Autowired
Controller で Repository を Autowired します。これで DB のデータを Controller で取得することが出来ます。
基本はこれだけです。
DBへの接続設定
ORACLE を使用する際には Spring Boot の apprication.properties に次の記述をします。(pom.xml の記述もお忘れなく!)
今回は findAll() で全レコード取得するだけでしたが、Spring Boot Data JPA にはたくさんの機能があり応用するともっと便利になります。