前言
本文介紹如何使用spring boot jpa repository如何使用該,本文承接上一篇文章工扎。本文介紹如何使用程序操作數(shù)據(jù)庫。
開發(fā)環(huán)境如下:
項目 | 說明 |
---|---|
jdk | 1.8 |
idea | 2017-03(已經(jīng)安裝lombok插件) |
mysql 5.6 | 推薦使用docker |
navicat | mysql 客戶端 |
操作步驟
- 新建repository類:AuthorRepository
package org.nick.bootstart.repositories;
import org.nick.bootstart.model.Author;
import org.springframework.data.repository.CrudRepository;
public interface AuthorRepository extends CrudRepository<Author,Long>{
}
- 新建控制類AuthorController
package org.nick.bootstart.controller;
import org.nick.bootstart.model.Author;
import org.nick.bootstart.repositories.AuthorRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class AuthorController {
AuthorRepository authorRepository;
public AuthorController(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@RequestMapping("/authors")
public String getAuthors(Model model){
Iterable<Author> authors = authorRepository.findAll();
model.addAttribute("authors",authorRepository.findAll());
return "authors";
}
}
- 新建模版文件:./src/main/resources/templates/authors.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleft.org">
<head>
<meta charset="UTF-8" >
<title>Title</title>
</head>
<body>
<h1>author list</h1>
<table>
<tr>
<th>id</th>
<th>frist name</th>
<th>last name</th>
</tr>
<tr th:each="author : ${authors}">
<td th:text="${author.id}"></td>
<td th:text="${author.firstName}"></td>
<td th:text="${author.lastName}"></td>
</tr>
</table>
</body>
</html>
- 執(zhí)行查看效果 .
image.png
總結(jié)
- 從數(shù)據(jù)庫中讀寫對象只需要實現(xiàn)CrudRepository類即可历等;
- 控制類可標(biāo)注
@Controller
序宦,對應(yīng)控制方法標(biāo)注@RequestMapping
,控制方法需要返回值為模版文件名字; - 使用模版文件为狸,需要在pom中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>