8月22日

Bookshelfを登録できるようにする

Repositoryを作成する。

src/main/java/
└jp.abc
 └BookshelfRepository.java

package jp.abc;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookshelfRepository extends JpaRepository<Bookshelf, Long> {

}

コントローラがPOSTメソッドを受け取れるようにする。

src/main/java/
└jp.abc
 └BookshelfController.java

package jp.abc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BookshelfController {

	@Autowired
	private BookshelfRepository repository;

	@RequestMapping(value = "/bookshelf", method = RequestMethod.GET)
	public ModelAndView index(ModelAndView mav) {
		mav.setViewName("bookshelf");
		mav.addObject("formModel", new Bookshelf());
		mav.addObject("datalist", repository.findAll());
		return mav;
	}

	@RequestMapping(value = "/bookshelf", method = RequestMethod.POST)
	public ModelAndView post(
			@ModelAttribute("formModel") @Validated Bookshelf bookshelf,
			Errors errors,
			ModelAndView mav) {
		if (errors.hasErrors()) {
			mav.addObject("msg", "エラーですよ");
			return mav;
		}
		repository.saveAndFlush(bookshelf);
		return new ModelAndView("redirect:/bookshelf");
	}
}

データベース接続設定を application.properties に記述する。

src/main/resources/
└application.properties

spring.datasource.url=jdbc:hsqldb:hsql://localhost/bookshelf
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.HSQLDialect
spring.jpa.hibernate.ddl-auto=update

本棚に収納するための本のクラス Book を作成する。

src/main/java/
└jp.abc
 └Book.java

package jp.abc;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

@Entity
public class Book {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column
	@NotNull
	private long id;

	@Column(length = 200, nullable = false)
	@NotEmpty
	private String title;

	@Column(length = 200, nullable = false)
	@NotEmpty
	private String author;

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

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

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

}

Book用のHTMLテンプレートを作成する。

src/main/resources/
└templates
 └book.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Book</title>
<style type="text/css">
h1 {
  font-size: 18pt;
  font-weight: bold;
  color: gray;
}
body {
  font-size: 13pt;
  color: gray;
  margin: 5px 25px;
}
tr {
  margin: 5px;
}
th {
  padding: 5px;
  color: white;
  background: darkgray;
}
td {
  padding: 5px;
  color: black;
  background: #f0f0f0;
}
.err {
  color: red;
}
</style>
</head>
<body>
<h1>Book</h1>
<p th:text="${msg}"></p>
<form method="post" action="/book" th:object="${formModel}">
  <table>
    <tr>
      <td><label for="title">タイトル</label></td>
      <td>
        <input type="text" name="title" th:value="*{title}"
      			th:errorclass="err" />
      	<div th:if="${#fields.hasErrors('title')}" th:errors="*{title}"
      		th:errorclass="err"></div>
      </td>
    </tr>
    <tr>
      <td><label for="author">著者</label></td>
      <td>
        <input type="text" name="author" th:value="*{author}"
      			th:errorclass="err" />
      	<div th:if="${#fields.hasErrors('author')}" th:errors="*{author}"
      		th:errorclass="err"></div>
      </td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" /></td>
    </tr>
  </table>
</form>

<hr />
<table>
  <tr>
    <th>ID</th><th>タイトル</th><th>著者</th>
  </tr>
  <tr th:each="obj : ${datalist}">
    <td th:text="${obj.id}"></td>
    <td th:text="${obj.title}"></td>
    <td th:text="${obj.author}"></td>
  </tr>
</table>

</body>
</html>

Book用のリポジトリを作成する。
src/main/java/
└jp.abc
 └BookRepository.java

package jp.abc;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {

}

Book用のコントローラを作成する。

src/main/java/
└jp.abc
 └BookController.java

package jp.abc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BookController {

	@Autowired
	private BookRepository repository;

	@RequestMapping(value = "/book", method = RequestMethod.GET)
	public ModelAndView index(ModelAndView mav) {
		mav.setViewName("book");
		mav.addObject("formModel", new Book());
		mav.addObject("datalist", repository.findAll());
		return mav;
	}

	@RequestMapping(value = "/book", method = RequestMethod.POST)
	public ModelAndView post(
			@ModelAttribute("formModel") @Validated Book book,
			Errors errors,
			ModelAndView mav) {
		if (errors.hasErrors()) {
			mav.addObject("msg", "エラーですよ");
			return mav;
		}
		repository.saveAndFlush(book);
		return new ModelAndView("redirect:/book");
	}
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください