今回もデータベースとのやりとりをやってみる。
Accessing JPA Data with RESTをやってみる
まずはbuild.gradleを編集する。
dependencies {
// compile("org.springframework.boot:spring-boot-starter-web:1.2.2.RELEASE")
// compile("org.springframework.boot:spring-boot-starter-actuator:1.2.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-thymeleaf:1.2.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-security:1.2.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-rest:1.2.2.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-jpa:1.2.2.RELEASE")
compile("com.h2database:h2:1.4.183")
compile("org.webjars:jquery:2.1.3")
testCompile("org.springframework.boot:spring-boot-starter-test:1.2.2.RELEASE")
}
Spring Bootのバージョンが1.2.2になったらしいので、全体的に1.2.2にしておいた。
ドメインオブジェクトを作る
Personクラスを定義する。
package sample;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
そしてPerson Repositoryを作成。
package sample;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(@Param("name") String name);
}
@RepositoryRestResourceアノテーションは、RESTfulなエンドポイントを作成する。ここでは/peopleになるように設定されているみたいだ。
これでgradle bootRunを実行すると、http://localhost:8080/peopleにRESTfulなエンドポイントが出来上がっていた。
実験的に、例であるようにcurlを使ってアクセスしてみる。
# GET
curl http://localhost:8080/people
# POST
curl -i -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Frodo", "lastName" : "Baggins" }' http://localhost:8080/people
# GET
curl http://localhost:8080/people/1
# PATCH
curl -X PATCH -H "Content-Type:application/json" -d '{ "firstName": "Bilbo Jr." }' http://localhost:8080/people/1
# GET
curl http://localhost:8080/people/search
# GET
curl http://localhost:8080/people/search/findByLastName?name=Baggins
@RepositoryRestResourceアノテーションを設定するだけでここまでやってくれるのはすごいなー。
次はHypermedia Driven REST web serviceをやってみようと思う。
というかそろそろなんか作ってみたほうがいいのかもしれない…。
