http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html

这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例。

先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个 Demo 来试试它的效果,越简单越容易上手最好。在网上找相关资料的时候总是很麻烦,有的文章写的挺不错的但是没有源代码,有的有源代码但是文章介绍又不是很清楚,所在找资料的时候稍微有点费劲。因此在我学习 Spring Boot 的时候,会写一些最简单基本的示例项目,一方面方便其它朋友以最快的方式去了解,一方面如果我的项目需要用到相关技术的时候,直接在这个示例版本去改造或者集成就可以。

现在的技术博客有很多的流派,有的喜欢分析源码,有的倾向于底层原理,我最喜欢写这种小而美的示例,方便自己方便他人。

其实以前写过 Thymeleaf 和 Jpa 的相关文章:Spring Boot (四): Thymeleaf 使用详解Spring Boot(五):Spring Data Jpa 的使用 里面的代码示例都给的云收藏的内容Favorites-web,云收藏的内容比较多,查找起来不是很方便,因此想重新整理一篇快速上手、简单的内容,来介绍 Jpa 和 Thymeleaf 的使用,也就是本文的内容。

这篇文章就不在介绍什么是 Jpa 、 Thymeleaf ,如果还不了解这些基本的概念,可以先移步前两篇相关文章。

快速上手

配置文件

pom 包配置

pom 包里面添加 Jpa 和 Thymeleaf 的相关包引用

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-data-jpa</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>mysql</groupId>
  15. <artifactId>mysql-connector-java</artifactId>
  16. </dependency>

在application.properties中添加配置

  1. spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
  2. spring.datasource.username=root
  3. spring.datasource.password=root
  4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  5. spring.jpa.properties.hibernate.hbm2ddl.auto=create
  6. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
  7. spring.jpa.show-sql= true
  8. spring.thymeleaf.cache=false

其中propertiesspring.thymeleaf.cache=false是关闭 Thymeleaf 的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为 true。

在项目 resources 目录下会有两个文件夹:static目录用于放置网站的静态内容如 css、js、图片;templates 目录用于放置项目使用的页面模板。

启动类

启动类需要添加 Servlet 的支持

  1. @SpringBootApplication
  2. public class JpaThymeleafApplication extends SpringBootServletInitializer {
  3. @Override
  4. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  5. return application.sources(JpaThymeleafApplication.class);
  6. }
  7. public static void main(String[] args) throws Exception {
  8. SpringApplication.run(JpaThymeleafApplication.class, args);
  9. }
  10. }

数据库层代码

实体类映射数据库表

  1. @Entity
  2. public class User {
  3. @Id
  4. @GeneratedValue
  5. private long id;
  6. @Column(nullable = false, unique = true)
  7. private String userName;
  8. @Column(nullable = false)
  9. private String password;
  10. @Column(nullable = false)
  11. private int age;
  12. ...
  13. }

继承 JpaRepository 类会自动实现很多内置的方法,包括增删改查。也可以根据方法名来自动生成相关 Sql,具体可以参考:Spring Boot (五):Spring Data Jpa 的使用

  1. public interface UserRepository extends JpaRepository<User, Long> {
  2. User findById(long id);
  3. Long deleteById(Long id);
  4. }

业务层处理

Service 调用 Jpa 实现相关的增删改查,实际项目中 Service 层处理具体的业务代码。

  1. @Service
  2. public class UserServiceImpl implements UserService{
  3. @Autowired
  4. private UserRepository userRepository;
  5. @Override
  6. public List<User> getUserList() {
  7. return userRepository.findAll();
  8. }
  9. @Override
  10. public User findUserById(long id) {
  11. return userRepository.findById(id);
  12. }
  13. @Override
  14. public void save(User user) {
  15. userRepository.save(user);
  16. }
  17. @Override
  18. public void edit(User user) {
  19. userRepository.save(user);
  20. }
  21. @Override
  22. public void delete(long id) {
  23. userRepository.delete(id);
  24. }
  25. }

Controller 负责接收请求,处理完后将页面内容返回给前端。

  1. @Controller
  2. public class UserController {
  3. @Resource
  4. UserService userService;
  5. @RequestMapping("/")
  6. public String index() {
  7. return "redirect:/list";
  8. }
  9. @RequestMapping("/list")
  10. public String list(Model model) {
  11. List<User> users=userService.getUserList();
  12. model.addAttribute("users", users);
  13. return "user/list";
  14. }
  15. @RequestMapping("/toAdd")
  16. public String toAdd() {
  17. return "user/userAdd";
  18. }
  19. @RequestMapping("/add")
  20. public String add(User user) {
  21. userService.save(user);
  22. return "redirect:/list";
  23. }
  24. @RequestMapping("/toEdit")
  25. public String toEdit(Model model,Long id) {
  26. User user=userService.findUserById(id);
  27. model.addAttribute("user", user);
  28. return "user/userEdit";
  29. }
  30. @RequestMapping("/edit")
  31. public String edit(User user) {
  32. userService.edit(user);
  33. return "redirect:/list";
  34. }
  35. @RequestMapping("/delete")
  36. public String delete(Long id) {
  37. userService.delete(id);
  38. return "redirect:/list";
  39. }
  40. }
  • return "user/userEdit"; 代表会直接去 resources 目录下找相关的文件。
  • return "redirect:/list"; 代表转发到对应的 Controller,这个示例就相当于删除内容之后自动调整到 list 请求,然后再输出到页面。

页面内容

list 列表

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>userList</title>
  6. <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
  7. </head>
  8. <body class="container">
  9. <br/>
  10. <h1>用户列表</h1>
  11. <br/><br/>
  12. <div class="with:80%">
  13. <table class="table table-hover">
  14. <thead>
  15. <tr>
  16. <th>#</th>
  17. <th>User Name</th>
  18. <th>Password</th>
  19. <th>Age</th>
  20. <th>Edit</th>
  21. <th>Delete</th>
  22. </tr>
  23. </thead>
  24. <tbody>
  25. <tr th:each="user : ${users}">
  26. <th scope="row" th:text="${user.id}">1</th>
  27. <td th:text="${user.userName}">neo</td>
  28. <td th:text="${user.password}">Otto</td>
  29. <td th:text="${user.age}">6</td>
  30. <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
  31. <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
  32. </tr>
  33. </tbody>
  34. </table>
  35. </div>
  36. <div class="form-group">
  37. <div class="col-sm-2 control-label">
  38. <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
  39. </div>
  40. </div>
  41. </body>
  42. </html>

效果图:

<tr th:each="user : ${users}"> 这里会从 Controler 层 model set 的对象去获取相关的内容,th:each表示会循环遍历对象内容。

其实还有其它的写法,具体的语法内容可以参考这篇文章:Spring Boot (四): Thymeleaf 使用详解

修改页面:

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>user</title>
  6. <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
  7. </head>
  8. <body class="container">
  9. <br/>
  10. <h1>修改用户</h1>
  11. <br/><br/>
  12. <div class="with:80%">
  13. <form class="form-horizontal" th:action="@{/edit}" th:object="${user}" method="post">
  14. <input type="hidden" name="id" th:value="*{id}" />
  15. <div class="form-group">
  16. <label for="userName" class="col-sm-2 control-label">userName</label>
  17. <div class="col-sm-10">
  18. <input type="text" class="form-control" name="userName" id="userName" th:value="*{userName}" placeholder="userName"/>
  19. </div>
  20. </div>
  21. <div class="form-group">
  22. <label for="password" class="col-sm-2 control-label" >Password</label>
  23. <div class="col-sm-10">
  24. <input type="password" class="form-control" name="password" id="password" th:value="*{password}" placeholder="Password"/>
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. <label for="age" class="col-sm-2 control-label">age</label>
  29. <div class="col-sm-10">
  30. <input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/>
  31. </div>
  32. </div>
  33. <div class="form-group">
  34. <div class="col-sm-offset-2 col-sm-10">
  35. <input type="submit" value="Submit" class="btn btn-info" />
  36. &nbsp; &nbsp; &nbsp;
  37. <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
  38. </div>
  39. </div>
  40. </form>
  41. </div>
  42. </body>
  43. </html>

添加页面和修改类似就不在贴代码了。

效果图:

这样一个使用 Jpa 和 Thymeleaf 的增删改查示例就完成了。

文章内容已经升级到 Spring Boot 2.x

当然所以的示例代码都在这里:

示例代码-github

示例代码-码云

(转)Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例的更多相关文章

  1. springboot(十五):springboot+jpa+thymeleaf增删改查示例

    这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个demo来试试它的效果,越简单越容易上 ...

  2. Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

    Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...

  3. Spring Boot (十五): Spring Boot + Jpa + Thymeleaf 增删改查示例

    这篇文章介绍如何使用 Jpa 和 Thymeleaf 做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个 Demo 来试试它的效果,越 ...

  4. Spring Boot + Jpa + Thymeleaf 增删改查示例

    快速上手 配置文件 pom 包配置 pom 包里面添加 Jpa 和 Thymeleaf 的相关包引用 <dependency> <groupId>org.springframe ...

  5. springboot+jpa+thymeleaf增删改查的示例(转)

    这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个demo来试试它的效果,越简单越容易上 ...

  6. spring boot2+jpa+thymeleaf增删改查例子

    参考这遍文章做了一个例子,稍微不同之处,原文是spring boot.mysql,这里改成了spring boot 2.Oracle. 一.pom.xml引入相关模块web.jpa.thymeleaf ...

  7. SpringBoot JPA + H2增删改查示例

    下面的例子是基于SpringBoot JPA以及H2数据库来实现的,下面就开始搭建项目吧. 首先看下项目的整体结构: 具体操作步骤: 打开IDEA,创建一个新的Spring Initializr项目, ...

  8. springBoot03- springboot+jpa+thymeleaf增删改查

    参考http://www.mooooc.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html 数据库: CREATE TABLE ...

  9. spring boot(十五)spring boot+thymeleaf+jpa增删改查示例

    快速上手 配置文件 pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 <dependency> <groupId>org.springframework.b ...

随机推荐

  1. SQL 注入漏洞

    首先要知道sql注入形成的原因:用户输入的数据被sql解释器执行 sql注入又分:数字型,字符型,cookie 注入,post注入,延时注入,搜索注入,base64注入 如何甄别一个模块是否有sql注 ...

  2. T-SQL基础(六)之可编程对象

    变量 -- 声明变量 DECLARE @variable_name [AS] variable_type; -- 变量赋值 SET @variable_name = variable_value; 示 ...

  3. Mybatis foreach标签含义

    背景 考虑以下场景: InfoTable(信息表): Name Gender Age Score 张三 男 21 90 李四 女 20 87 王五 男 22 92 赵六 女 19 94 孙七 女 23 ...

  4. Angular6 组件树结构优化

    本片博客主要是记录实际项目开发中使用Angular6框架,遇到的一个问题. 现象: Angular6框架写的前端web网页,在实际部署运行过程中遇到了一种现象,引入懒加载以后,加载登录面速度很快,但是 ...

  5. angular 用拦截器统一处理http请求和响应 比如加token

    想使用angularjs里的htpp向后台发送请求,现在有个用户唯一识别的token想要放到headers里面去,也就是{headres:{'token':1}} index.html里引入以下js: ...

  6. Vue2+VueRouter2+webpack 构建项目实战(三):配置路由,运行页面

    制作.vue模板文件 通过前面的两篇博文的学习,我们已经建立好了一个项目.问题是,我们还没有开始制作页面.下面,我们要来做页面了. 我们还是利用 http://cnodejs.org/api 这里公开 ...

  7. 学习之路-前端-笔记-一、HTML笔记

    各种技巧 1.在Webstrom中 同时按ctrl+alt+insert创建新内容 2.输入标签按tab自动补全 按end 或 HOME实现光标移动到当前行的最后或最前 3.按住alt键不放同时按鼠标 ...

  8. Android Studio Git 分支使用实践

    新公司有些项目是用的 Git,以前公司都是 svn,为了练手 Git,我个人 APP 用到了,但是仅简单的 git pull/push 的使用,并未用到 Git 精髓,只有当项目中用到,才会紧迫去全面 ...

  9. 机器学习之EM算法(五)

    摘要 EM算法全称为Expectation Maximization Algorithm,既最大期望算法.它是一种迭代的算法,用于含有隐变量的概率参数模型的最大似然估计和极大后验概率估计.EM算法经常 ...

  10. RMAN restore fails with ORA-01180: can not create datafile 1

      最近在验证.测试备份有效性时,遇到了"ORA-01180: can not create datafile 1"这个错误,顺便结合metalink的官方文档"RMAN ...