前言
本文介绍如何使用spring boot jpa repository如何使用该,本文承接上一篇文章。本文介绍如何使用程序操作数据库。
开发环境如下:
项目 | 说明 |
---|---|
jdk | 1.8 |
idea | 2017-03(已经安装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>
- 执行查看效果 .
总结
- 从数据库中读写对象只需要实现CrudRepository类即可;
- 控制类可标注
@Controller
,对应控制方法标注@RequestMapping
,控制方法需要返回值为模版文件名字; - 使用模版文件,需要在pom中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>