這篇文章介紹如何使用 Jpa 和 Thymeleaf 作一個增刪改查的示例。css
先和你們聊聊我爲何喜歡寫這種腳手架的項目,在我學習一門新技術的時候,老是想快速的搭建起一個 Demo 來試試它的效果,越簡單越容易上手最好。在網上找相關資料的時候老是很麻煩,有的文章寫的挺不錯的可是沒有源代碼,有的有源代碼可是文章介紹又不是很清楚,所在找資料的時候稍微有點費勁。所以在我學習 Spring Boot 的時候,會寫一些最簡單基本的示例項目,一方面方便其它朋友以最快的方式去了解,一方面若是個人項目須要用到相關技術的時候,直接在這個示例版本去改造或者集成就能夠。html
如今的技術博客有不少的流派,有的喜歡分析源碼,有的傾向於底層原理,我最喜歡寫這種小而美的示例,方便本身方便他人。前端
其實之前寫過 Thymeleaf 和 Jpa 的相關文章:Spring Boot (四): Thymeleaf 使用詳解和Spring Boot(五):Spring Data Jpa 的使用 裏面的代碼示例都給的雲收藏的內容Favorites-web,雲收藏的內容比較多,查找起來不是很方便,所以想從新整理一篇快速上手、簡單的內容,來介紹 Jpa 和 Thymeleaf 的使用,也就是本文的內容。java
這篇文章就不在介紹什麼是 Jpa 、 Thymeleaf ,若是還不瞭解這些基本的概念,能夠先移步前兩篇相關文章。mysql
pom 包配置git
pom 包裏面添加 Jpa 和 Thymeleaf 的相關包引用github
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
在application.properties中添加配置web
spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=create spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true spring.thymeleaf.cache=false
其中propertiesspring.thymeleaf.cache=false
是關閉 Thymeleaf 的緩存,否則在開發過程當中修改頁面不會馬上生效須要重啓,生產可配置爲 true。spring
在項目 resources 目錄下會有兩個文件夾:static目錄用於放置網站的靜態內容如 css、js、圖片;templates 目錄用於放置項目使用的頁面模板。sql
啓動類須要添加 Servlet 的支持
@SpringBootApplication public class JpaThymeleafApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(JpaThymeleafApplication.class); } public static void main(String[] args) throws Exception { SpringApplication.run(JpaThymeleafApplication.class, args); } }
實體類映射數據庫表
@Entity public class User { @Id @GeneratedValue private long id; @Column(nullable = false, unique = true) private String userName; @Column(nullable = false) private String password; @Column(nullable = false) private int age; ... }
繼承 JpaRepository 類會自動實現不少內置的方法,包括增刪改查。也能夠根據方法名來自動生成相關 Sql,具體能夠參考:Spring Boot (五):Spring Data Jpa 的使用
public interface UserRepository extends JpaRepository<User, Long> { User findById(long id); Long deleteById(Long id); }
Service 調用 Jpa 實現相關的增刪改查,實際項目中 Service 層處理具體的業務代碼。
@Service public class UserServiceImpl implements UserService{ @Autowired private UserRepository userRepository; @Override public List<User> getUserList() { return userRepository.findAll(); } @Override public User findUserById(long id) { return userRepository.findById(id); } @Override public void save(User user) { userRepository.save(user); } @Override public void edit(User user) { userRepository.save(user); } @Override public void delete(long id) { userRepository.delete(id); } }
Controller 負責接收請求,處理完後將頁面內容返回給前端。
@Controller public class UserController { @Resource UserService userService; @RequestMapping("/") public String index() { return "redirect:/list"; } @RequestMapping("/list") public String list(Model model) { List<User> users=userService.getUserList(); model.addAttribute("users", users); return "user/list"; } @RequestMapping("/toAdd") public String toAdd() { return "user/userAdd"; } @RequestMapping("/add") public String add(User user) { userService.save(user); return "redirect:/list"; } @RequestMapping("/toEdit") public String toEdit(Model model,Long id) { User user=userService.findUserById(id); model.addAttribute("user", user); return "user/userEdit"; } @RequestMapping("/edit") public String edit(User user) { userService.edit(user); return "redirect:/list"; } @RequestMapping("/delete") public String delete(Long id) { userService.delete(id); return "redirect:/list"; } }
return "user/userEdit";
表明會直接去 resources 目錄下找相關的文件。return "redirect:/list";
表明轉發到對應的 Controller,這個示例就至關於刪除內容以後自動調整到 list 請求,而後再輸出到頁面。list 列表
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>userList</title> <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link> </head> <body class="container"> <br/> <h1>用戶列表</h1> <br/><br/> <div class="with:80%"> <table class="table table-hover"> <thead> <tr> <th>#</th> <th>User Name</th> <th>Password</th> <th>Age</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr th:each="user : ${users}"> <th scope="row" th:text="${user.id}">1</th> <td th:text="${user.userName}">neo</td> <td th:text="${user.password}">Otto</td> <td th:text="${user.age}">6</td> <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td> <td><a th:href="@{/delete(id=${user.id})}">delete</a></td> </tr> </tbody> </table> </div> <div class="form-group"> <div class="col-sm-2 control-label"> <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a> </div> </div> </body> </html>
效果圖:
<tr th:each="user : ${users}">
這裏會從 Controler 層 model set 的對象去獲取相關的內容,th:each
表示會循環遍歷對象內容。
其實還有其它的寫法,具體的語法內容能夠參考這篇文章:Spring Boot (四): Thymeleaf 使用詳解
修改頁面:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>user</title> <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link> </head> <body class="container"> <br/> <h1>修改用戶</h1> <br/><br/> <div class="with:80%"> <form class="form-horizontal" th:action="@{/edit}" th:object="${user}" method="post"> <input type="hidden" name="id" th:value="*{id}" /> <div class="form-group"> <label for="userName" class="col-sm-2 control-label">userName</label> <div class="col-sm-10"> <input type="text" class="form-control" name="userName" id="userName" th:value="*{userName}" placeholder="userName"/> </div> </div> <div class="form-group"> <label for="password" class="col-sm-2 control-label" >Password</label> <div class="col-sm-10"> <input type="password" class="form-control" name="password" id="password" th:value="*{password}" placeholder="Password"/> </div> </div> <div class="form-group"> <label for="age" class="col-sm-2 control-label">age</label> <div class="col-sm-10"> <input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" value="Submit" class="btn btn-info" /> <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a> </div> </div> </form> </div> </body> </html>
添加頁面和修改相似就不在貼代碼了。
效果圖:
這樣一個使用 Jpa 和 Thymeleaf 的增刪改查示例就完成了。
文章內容已經升級到 Spring Boot 2.x
固然因此的示例代碼都在這裏: