0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring BootでDBの値を返す簡単なAPIの構築手順

0
Posted at

Spring BootでDBの値を返す簡単なAPIの構築手順を紹介します。

まずは、プロジェクトをビルドします。
その際に、下記のライブラリを入れておきます。

・H2 Database
・Spring Data JPA
・Spring Boot DevTools
・Spring Web

ビルドの際に入れ忘れた、後から追加する場合は
build.gradeのdependenciesを下記のように編集すればOKです

build.grade
dependencies {
	implementation 'org.springframework.boot:spring-boot-h2console'
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-webmvc'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	runtimeOnly 'com.h2database:h2'
	testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
	testImplementation 'org.springframework.boot:spring-boot-starter-webmvc-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

まずは、ビルドに作成された〇〇Apolication.javaを編集します

package com.project.backend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;



//
import java.time.LocalDateTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;

//import com.project.backend.database.PostdatabaseApplication;
import com.project.backend.domain.Post;
import com.project.backend.domain.PostRepository;

//

@SpringBootApplication
public class BackendApplication implements CommandLineRunner{

	private static final Logger logger = LoggerFactory.getLogger(BackendApplication.class);
    private final PostRepository repository;
    public BackendApplication(PostRepository repository){
        this.repository = repository;
    }

	//ここは元からあった記述
	public static void main(String[] args) {
		SpringApplication.run(BackendApplication.class, args);
	}

	//CommandLineRunnerのメソッドをオーバーライド
	@Override
    public void run(String ...args) throws Exception{
        repository.save(new Post("Hello World","これはテストの投稿。CommandLineRunnerのサブクラスより。","",LocalDateTime.now(), LocalDateTime.now()));
        // for (Post post:repository.findAll(){
        //     logger.info
        // });
    }

}

パッケージとファイルを作成します。
今回は、domainとwebというパッケージを作り、その中にファイルを作りました。
この辺はパッケージの名前や配置場所に制限はないので自分の好きな構成でもOKです。
image.png

domain
・Post.java(DBモデル)
・PostRepositor.java(DBモデル操作)

web
・PostController.java(コントローラ)

各ファイル

Post.java
package com.project.backend.domain;
import jakarta.persistence.Entity;//JPAのパッケージ使用
import jakarta.persistence.GeneratedValue;//JPAのパッケージ使用
import jakarta.persistence.GenerationType;//JPAのパッケージ使用
import jakarta.persistence.Id;//JPAのパッケージ使用

import java.time.LocalDateTime;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

//@Entityをつけると、クラスをDBのモデルとして、変数をカラムにできる
@Entity
public class Post {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String title, body, image;
    
    @CreationTimestamp
    private LocalDateTime createdAt;

    @UpdateTimestamp
    private LocalDateTime updatedAt;

    public Post(){

    }

    public Post(String title,String body,String image, LocalDateTime createdAt,LocalDateTime updatedAt){
        super();
        this.title = title;
        this.body = body;
        this.image = image;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }

    public Long getId(){
        return id;
    }

    public String getTitle(){
        return title;
    }

    public void setTitle(String title){
        this.title = title;
    }

    public String getBody(){
        return body;
    }

    public void setBody(String body){
        this.body = body;
    }

    public String getImage(){
        return image;
    }

    public void setImage(String image){
        this.image = image;
    }

    public LocalDateTime getCreatedAt(){
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt){
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt(){
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt){
        this.updatedAt = updatedAt;
    }

}

PostRepositor.java
package com.project.backend.domain;

import org.springframework.data.repository.CrudRepository;;

public interface PostRepository extends CrudRepository <Post, Long>{
    
}

PostController.java
package com.project.backend.web;

import org.springframework.web.bind.annotation.GetMapping; // Adress for Get request
import org.springframework.web.bind.annotation.RestController; // Marks this class as a RESTful web service controlle
import com.project.backend.domain.Post; // Call Post DB Model
import com.project.backend.domain.PostRepository;

@RestController
public class PostController {

    //inject(DI) PostRepository
    private final PostRepository repository; // to be able to return posts from DB

    //constructor
    public PostController(PostRepository repository){
        this.repository = repository;
    }

    //[end point URL] return all posts
    @GetMapping("/posts")
    public Iterable<Post> getPosts(){
        //findAllメソッドは、CrudRepositoryで定義されたメソッド。
        //PostRepositoryで継承して使用できている
        return repository.findAll();
    }
    
}

これで、完成です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?