Thymeleafを使用したSpring Boot CRUDアプリケーション
1. 概要
JPAエンティティにCRUD機能を提供するDAOレイヤーの実装は、ほとんどの場合避けたい反復的で時間のかかるタスクになる可能性があります。 幸い、Spring Bootを使用すると、標準のJPAベースのCRUDリポジトリのレイヤーを介してCRUDアプリケーションを簡単に作成できます。
In this tutorial, we’ll learn how to develop a CRUD web application with Spring Boot and Thymeleaf。
参考文献:
2. Mavenの依存関係
この場合、単純な依存関係の管理、バージョン管理、プラグインの構成をspring-boot-starter-parentに依存します。 その結果、Javaバージョンをオーバーライドする場合を除いて、pom.xmlファイルでプロジェクトの依存関係のバージョンを指定する必要はありません。
org.springframework.boot
spring-boot-starter-parent
2.0.6.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-data-jpa
com.h2database
h2
1.8
spring-boot-starter-parentが定義するデフォルトのJavaバージョンは1.6であるため、<java.version>プロパティをオーバーライドする必要があります。
3. ドメインレイヤー
プロジェクトの依存関係がすべて整ったところで、ナイーブなドメインレイヤーを実装しましょう。
簡単にするために、このレイヤーには、Userエンティティのモデリングを担当する単一のクラスが含まれます。
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
// standard constructors / setters / getters / toString
}
クラスに@Entityアノテーションを付けたことを覚えておいてください。 Therefore, the JPA implementation, which is Hibernate, in this case, will be able to perform CRUD operations on the domain entities. Hibernateの入門ガイドについては、Hibernate 5 with Springに関するチュートリアルにアクセスしてください。
さらに、nameフィールドとemailフィールドを@NotBlank制約で制約しました。 これは、データベース内のエンティティを永続化または更新する前に、Hibernate Validatorを使用して制約されたフィールドを検証できることを意味します。
これに関する基本については、our associated tutorial on Bean Validationを確認してください。
4. リポジトリ層
この時点で、サンプルWebアプリケーションは何もしません。 しかし、それはもうすぐ変わります。
Spring Data JPAallows us to implement JPA-based repositories (a fancy name for the DAO pattern implementation) with minimal fuss。
Spring Data JPAは、Spring Bootのspring-boot-starter-data-jpaの重要なコンポーネントであり、JPA実装の上に配置された強力な抽象化レイヤーを通じてCRUD機能を簡単に追加できます。 この抽象化レイヤーにより、独自のDAO実装をゼロから提供することなく、永続レイヤーにアクセスできます。
アプリケーションにUserオブジェクトの基本的なCRUD機能を提供するには、CrudRepositoryインターフェイスを拡張するだけです。
@Repository
public interface UserRepository extends CrudRepository {}
以上です! Spring Data JPAは、CrudRepositoryインターフェースを拡張するだけで、リポジトリーのCRUDメソッドの実装を提供します。
5. コントローラー層
Thanks to the layer of abstraction that spring-boot-starter-data-jpa places on top of the underlying JPA implementation, we can easily add some CRUD functionality to our web application through a basic web tier。
この場合、GETおよびPOST HTTPリクエストを処理し、それらをUserRepository実装への呼び出しにマップするには、単一のコントローラークラスで十分です。
コントローラクラスは、SpringMVCの主要な機能のいくつかに依存しています。 Spring MVCの詳細なガイドについては、Spring MVC tutorialを確認してください。
コントローラのshowSignUpForm()メソッドとaddUser()メソッドから始めましょう。
前者はユーザーサインアップフォームを表示し、後者は制約されたフィールドを検証した後、データベースに新しいエンティティを保持します。
エンティティが検証に合格しなかった場合、登録フォームが再表示されます。 それ以外の場合、エンティティが保存されると、永続化されたエンティティのリストが対応するビューで更新されます。
@Controller
public class UserController {
@GetMapping("/signup")
public String showSignUpForm(User user) {
return "add-user";
}
@PostMapping("/adduser")
public String addUser(@Valid User user, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
// additional CRUD methods
}
UserController we内には、データベースから提供されたidと一致するUserエンティティをフェッチするshowUpdateForm()メソッドもあります。
エンティティが存在する場合は、モデル属性として更新フォームビューに渡されるため、フォームにnameフィールドとemailフィールドの値を入力できます。
@GetMapping("/edit/{id}")
public String showUpdateForm(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
model.addAttribute("user", user);
return "update-user";
}
最後に、UserControllerクラス内にupdateUser()メソッドとdeleteUser()メソッドがあります。
最初のものは更新されたエンティティをデータベースに保持し、最後のものは特定のエンティティを削除します。
どちらの場合でも、永続化されたエンティティのリストはそれに応じて更新されます。
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid User user,
BindingResult result, Model model) {
if (result.hasErrors()) {
user.setId(id);
return "update-user";
}
userRepository.save(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable("id") long id, Model model) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
model.addAttribute("users", userRepository.findAll());
return "index";
}
6. ビューレイヤー
この時点で、Userエンティティに対してCRUD操作を実行する機能コントローラークラスを実装しました。 Even so, there’s still a missing component in this schema: the view layer.
src/main/resources/templatesフォルダーの下に、サインアップフォーム、更新フォームの表示、および永続化されたUserエンティティのリストのレンダリングに必要なHTMLテンプレートを作成する必要があります。
はじめに述べたように、テンプレートファイルを解析するための基盤となるテンプレートエンジンとしてThymeleafを使用します。
add-user.htmlファイルの関連セクションは次のとおりです。
Notice how we’ve used the @\{/adduser} URL expression to specify the form’s action attribute and the $\{} variable expressions for embedding dynamic content in the template, such as the values of the name and email fields and the post-validation errors。
add-user.htmlと同様に、update-user.htmlテンプレートの外観は次のとおりです。
最後に、永続化されたエンティティのリストと、既存のエンティティを編集および削除するためのリンクを表示するindex.htmlファイルがあります。
簡単にするために、テンプレートはかなり骨格的に見え、不要なcosmeticsを追加せずに必要な機能のみを提供します。
HTML / CSSに多くの時間を費やすことなく、テンプレートの外観を改善して人目を引くようにするために、Shardsなどの無料のTwitter BootstrapUIキットを簡単に使用できます。
7. アプリケーションを実行する
最後に、アプリケーションのエントリポイントを定義しましょう。 ほとんどのSpringBootアプリケーションと同様に、これは単純な古いmain()メソッドで実行できます。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
それでは、IDEで「実行」をクリックしてから、ブラウザを開いてhttp://localhost:8080をポイントします。
ビルドがwe should see a basic CRUD user dashboard with links for adding new entities and for editing and removing existing ones.を正常にコンパイルした場合
8. 結論
このチュートリアルでは、Spring BootとThymeleafを使用して基本的なCRUD Webアプリケーションを構築する方法を学びました。
いつものように、記事に示されているすべてのコードサンプルはon GitHubで利用できます。