iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐥

Creating a REST API with Java, Spring Boot, PostgreSQL, and Spring Data REST

に公開3件

Finally, "docker-compose" is no longer in the title lol

TL;DR

Preparing to use Spring Data REST

I briefly mentioned Spring Data REST in the article below, but it is a convenient package that generates all RESTful endpoints just by preparing Entities and Repositories.

So, even though I say "preparation," it just involves adding implementation 'org.springframework.boot:spring-boot-starter-data-rest' to server/build.gradle from the state of the previous article.

server/build.gradle
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-rest'
...

In Spring Initializr, it looks like this.

No code changes are required from the state of the previous article. Amazing (pardon my elementary-level excitement).

Starting the Docker container, building with Gradle, starting the application, and sending requests

docker-compose up -d
# It takes a bit for the DB to start up and initialize, so wait a moment
docker-compose exec app bash
bash-4.4# sh gradlew build
...
BUILD SUCCESSFUL in 8m 41s
5 actionable tasks: 5 executed
# Verify it's created
bash-4.4# ls build/libs/
app-0.0.1-SNAPSHOT.jar
bash-4.4# java -jar build/libs/app-0.0.1-SNAPSHOT.jar

Once it's started, let's send a request.

$ curl http://localhost:8080/users -X GET
{
  "_embedded" : {
    "users" : [ {
      "name" : "test",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        },
        "user" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/users"
    }
  }
}

It works! Awesome!
You can also register data with a POST request.

$ curl http://localhost:8080/users -X POST -H "Content-Type:application/json" -d '{ "name":"foo" }'
{
  "name" : "foo",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/2"
    },
    "user" : {
      "href" : "http://localhost:8080/users/2"
    }
  }
}
$ curl http://localhost:8080/users -X POST -H "Content-Type:application/json" -d '{ "name":"bar" }'
{
  "name" : "bar",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/3"
    },
    "user" : {
      "href" : "http://localhost:8080/users/3"
    }
  }
}

Let's try a GET request again.

curl http://localhost:8080/users -X GET
{
  "_embedded" : {
    "users" : [ {
      "name" : "test",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/1"
        },
        "user" : {
          "href" : "http://localhost:8080/users/1"
        }
      }
    }, {
      "name" : "foo",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/2"
        },
        "user" : {
          "href" : "http://localhost:8080/users/2"
        }
      }
    }, {
      "name" : "bar",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/users/3"
        },
        "user" : {
          "href" : "http://localhost:8080/users/3"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/users"
    }
  }
}

Of course, you can also GET only a specific piece of data by specifying the ID in the URI.

$ curl http://localhost:8080/users/3 -X GET
{
  "name" : "bar",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/3"
    },
    "user" : {
      "href" : "http://localhost:8080/users/3"
    }
  }
}

You can also update data with a PUT request.

$ curl http://localhost:8080/users/3 -X PUT -H "Content-Type:application/json" -d '{ "name":"piyo" }'
{
  "name" : "piyo",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/3"
    },
    "user" : {
      "href" : "http://localhost:8080/users/3"
    }
  }
}
$ curl http://localhost:8080/users/3 -X GET
{
  "name" : "piyo",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/users/3"
    },
    "user" : {
      "href" : "http://localhost:8080/users/3"
    }
  }
}

Wow. This is really something.
Let's log into Adminer at http://localhost:9000 to see if the data is actually registered in the database.

It is registered! OK!
If you want to set up an extremely simple RESTful API, this might even be faster than Rails... lol

Troubleshooting: When registration via POST fails

Depending on the state of your code, you might get a 500 ERROR when sending a POST request.
You can check the nature of the error in the logs where the Spring Boot application is running by executing java -jar build/libs/app-0.0.1-SNAPSHOT.jar.

ERROR: relation "hibernate_sequence" does not exist

There is a possibility that the mapping for the @GeneratedValue in your Entity class against the PostgreSQL SERIAL column is incorrect.
In the case of this code, please check the following part:

server/src/main/java/com/example/app/entity/User.java
package com.example.app.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

  @Id
  // Check if this is @GeneratedValue(strategy = GenerationType.IDENTITY)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;

  protected User() {}

  public User(String name) {
    this.name = name;
  }

  public Long getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return String.format("{id:%d,name:%s}", id, name);
  }
}

ERROR:permission denied for sequence user_id_seq

In this setup, we created a user called appuser to connect from the app server to PostgreSQL. If appuser does not have SELECT permission on SEQUENCES, an error will occur when issuing an id increment for the SERIAL column.

In the case of this code, please check the following part:

forDocker/db/initdb/3_create_role_appuser.sql
CREATE ROLE appuser WITH LOGIN PASSWORD 'apppass';
GRANT SELECT,UPDATE,INSERT,DELETE ON ALL TABLES IN SCHEMA public TO appuser;
-- Check if the line below is correctly included
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO appuser;

Note that if you edit the queries under forDocker/db/initdb, since this docker-compose.yml has a docker volume assigned, you can have it re-executed by deleting dbvol with docker volume rm ....


The repository for this article can be found here.
https://github.com/JUNKI555/java_spring_boot_practice02

References

Discussion

北山淳也北山淳也

「今回のコードであれば以下の部分を確認してみてください。」とか
偉そうに書いてるけど今回の記事を書き始めてから前回の記事を修正したのは内緒です(これが原因でハマッた人がいたらごめんなさい、のでトラブルシュートとして書きました🙇‍♂️)

1
catnosecatnose

タイトル制限とりあえず近いうちに+10字します…😹

1
北山淳也北山淳也

@catnose さん
ありがとうございます!私ももうちょっとシンプルにタイトルつけるようにします 🙇‍♂️

1