快速上手

配置文件

pom 包配置

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

<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中添加配置

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。

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

启动类

启动类需要添加 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" />
&nbsp; &nbsp; &nbsp;
<a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
</div> </div>
</form>
</div>
</body>
</html>

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

效果图:

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

Spring Boot + Jpa + Thymeleaf 增删改查示例的更多相关文章

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

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

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

    http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html 这篇文章介绍如何使用 Jpa 和 ...

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

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

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

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

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

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

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

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

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

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

  8. Spring Date JPA实现增删改查

    1.新建一个Cart类 package com.entity; public class Cart { private int id; private int userId; private int ...

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

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

随机推荐

  1. Docker:镜像构建与进入容器总结

    构建镜像总结 docker构建镜像有两种方法: 1.使用docker commit + 容器 docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] ...

  2. .NET 4.5 中新提供的压缩类(转载)

    Windows8 的开发已经如火如荼开始了,在 Windows8 中提供的 .NET Framework 已经更新到了 4.5 版,其中又增加了一些新的特性,对压缩文件的支持就是其中之一. 在 4.5 ...

  3. caffe运行报错:datum channel>0(0:0)

    caffe在运行的时候报错:datum channel>0(0:0) 错误原因:数据通道错误,caffe不能识别 解决方案:不告诉你

  4. 记录在tiny6410平台上采用4GSD卡来启动uboot和烧写nand flash uboot

    下面这种方法是从网上转的 没有验证 环境:ubuntu 13.04一.首先制作sd启动盘: 插入SD卡    sudo dd iflag=dsync oflag=dsync if=tiny210v2- ...

  5. 移动端长按响应事件以及阻止默认行为e.preventDefault()导致定时器setTimeout不能响应

    手指触摸绑定: $(document).on('touchstart', '.photo', function(e){ currentIndex = parseInt($(this).index('. ...

  6. SQL语句汇总(二)——数据修改、数据查询

    SQL语句第二篇,不说废话直接开始吧. 首先创建一张表如下,创建表的方法在上篇介绍过了,这里就不再赘述. 添加新数据: INSERT INTO <表名> (<列名列表>) VA ...

  7. Mysql 集合链接查询

    MySQL NULL 值处理 需求:我们已经知道MySQL使用 SQL SELECT 命令及 WHERE 子句来读取数据表中的数据,但是当提供的查询条件字段为 NULL 时,该命令可能就无法正常工作. ...

  8. java.lang.IllegalArgumentException: An invalid domain [.test.com] was specified for this cookie解决方法

    当项目中使用单点登录功能时,通常会使用cookie进行信息的保存,这样就可以在多个子域名上存取用户信息. 比如有三个domain分别为test.com,cml.test.com,b.test.com这 ...

  9. 关于ashrpt中行源的CPU + Wait for CPU事件深入解读

    该等待事件并不包含在等待事件范围,而是出现在ash的具体行源中,如下: 标注语句的每次执行大约1小时,如下awr所示: 该sql语句的最后一层Insert如下: insert into ta_tf l ...

  10. python 排序算法

    冒泡排序: 一. 冒泡排序的定义 冒泡排序(英语:Bubble Sort)是一种简单的排序算法.它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来.遍历数列的工作是重复地进 ...