Spring boot2+jpa+thymeleaf实现增删改查
作者:gdjlc 发布时间:2021-06-02 07:21:49
一、pom.xml引入相关模块web、jpa、thymeleaf、oracle:
<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>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>
二、application.properties配置
server.port = 9001
spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:testdb
spring.datasource.username = dev
spring.datasource.password = dev
spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql = true
spring.thymeleaf.cache = false
说明:
1、由于本机的8080已经被使用,修改一下端口号为9001。
2、hibernate.hbm2ddl.auto参数有四个值:
create: 每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要
这样执行,这就是导致数据库表数据丢失的一个重要原因。
create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载
hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
3、show-sql 是否打印出自动生产的SQL,方便调试的时候查看
4、propertiesspring.thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产
可配置为true。
三、启动类需要添加Servlet的支持
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
四、数据库层代码
1、实体类映射数据库表
package com.example.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Length;
@Entity
@Table(name = "userinfo")
public class User {
@Id
@GeneratedValue
private long id;
@Column(nullable = false, unique = true)
@NotEmpty(message="用户名不能为空")
private String userName;
@Column(nullable = false)
@NotEmpty(message="密码不能为空")
@Length(min=6, message="密码长度不能少于6位")
private String password;
@Column(nullable = false)
private int age;
//必须有构造
public User() {
}
public long getId() {
return id;
}
public User setId(long id) {
this.id = id;
return this;
}
public String getUserName() {
return userName;
}
public User setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public int getAge() {
return age;
}
public User setAge(int age) {
this.age = age;
return this;
}
}
2、继承JpaRepository类会自动实现很多内置的方法
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findById(long id);
void deleteById(Long id);
}
五、业务层
service调用jpa实现相关的增删改查,实际项目中service层处理具体的业务代码。
1、UserService.java
package com.example.demo.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.example.demo.entity.User;
public interface UserService {
public Page<User> getUserPage(Pageable pageable);
public List<User> getUserList();
public User findUserById(long id);
public void save(User user);
public void edit(User user);
public void delete(long id);
}
2、UserServiceImpl.java
package com.example.demo.service.impl;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public Page<User> getUserPage(Pageable pageable) {
return userRepository.findAll(pageable);
}
@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.deleteById(id);
}
}
六、控制层
package com.example.demo.web.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
@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);
/*int page=1,size=2;
Sort sort = new Sort(Direction.DESC, "id");
Pageable pageable = PageRequest.of(page, size, sort);
model.addAttribute("users", pageable);*/
return "user/list";
}
@RequestMapping("/toAdd")
public String toAdd() {
return "user/userAdd";
}
@RequestMapping("/add")
public @ResponseBody User add(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getDefaultMessage());
}
return null;
}
userService.save(user);
return user;
}
@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";
}
}
七、页面
1、列表页 list.hmtl
<!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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></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})}" rel="external nofollow" >edit</a></td>
<td><a th:href="@{/delete(id=${user.id})}" rel="external nofollow" >delete</a></td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="col-sm-2 control-label">
<a href="/toAdd" rel="external nofollow" rel="external nofollow" th:href="@{/toAdd}" rel="external nofollow" class="btn btn-info">add</a>
</div>
</div>
</body>
</html>
2、新增页 userAdd.html
<!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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></link>
</head>
<body class="container">
<br/>
<h1>添加用户</h1>
<br/><br/>
<div class="with:80%">
<form class="form-horizontal" th:action="@{/add}" method="post">
<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" 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" 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" 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" />
<input type="reset" value="Reset" class="btn btn-info" />
</div>
</div>
</form>
</div>
</body>
</html>
3、修改页 userEdit.html
<!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}" rel="external nofollow" rel="external nofollow" rel="external nofollow" ></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" rel="external nofollow" rel="external nofollow" th:href="@{/list}" rel="external nofollow" class="btn btn-info">Back</a>
</div>
</div>
</form>
</div>
</body>
</html>
来源:https://www.cnblogs.com/gdjlc/p/10039494.html
猜你喜欢
- C# WinForm控件的拖动和缩放是个很有用的功能。实现起来其实很简单的,主要是设计控件的MouseDown、MouseLeave、Mou
- 一、PriorityQueue的数据结构JDK7中PriorityQueue(优先级队列)的数据结构是二叉堆。准确的说是一个最小堆。二叉堆是
- 本文实例讲述了C#中lock的用法。分享给大家供大家参考。具体分析如下:lock 关键字可以用来确保代码块完成运行,而不会被其他线程中断。这
- 本文实例为大家分享了DatePicker日期滚动选择的使用,供大家参考,具体内容如下效果图为:1.dialog_date.xml:<?
- Java 内存划分: 在Java内存分配中,java将内存分为:方法区,堆,虚拟机栈,本地方法栈,程序计
- drawerLayout是Support Library包中实现了侧滑菜单效果的控件,可以说drawerLayout是因为第三方控件如Men
- 本文实例为大家分享了Android实现图片点击 * 效果的具体代码,供大家参考,具体内容如下实现效果:需要注意的点:ValueAnimator
- 一,FileWritter写入文件FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,然而,当指
- 我们在shader中对贴图处理时,有时候会有一些比较复杂的运算,比方说三角函数,开方等,一般情况下,如果可以在越上层做运算,性能会越高。C#
- 一、配置xml路径mybatis-plus:mapper-locations: classpath:mapper/*.xml二、编写Mapp
- 本文实例为大家分享了iOS新浪微博分享功能的具体代码,供大家参考,具体内容如下做新浪分享 需先去http://open.weibo.com/
- DataGridView:显示数据表后台数据绑定:List<xxx> list = new List<xxx>();
- foreach 循环 list(map)直接上代码:整体需求就是1.分页对象里面有map map里面又有数组对象2.分页对象里面有list
- 因为最近用报表导出比较多,所有就提成了一个工具类,本工具类使用的场景为 根据提供的模板来导出Excel报表并且可根据提供的模板S
- ES是一个基于Lucene的分布式全文搜索服务器,和SQL Server的全文索引(Fulltext Index)有点类似,都是基于分词和分
- 本文实例讲述了spring AOP的After增强实现方法。分享给大家供大家参考,具体如下:一 配置<?xml version=&qu
- 俄罗斯方块Tetris是一款很经典的益智游戏,之前就做了一款桌面版的java俄罗斯方块,这次就尝试着写了一款适用于Android平台的俄罗斯
- Handler是用于操作线程内部的消息队列的类。这有点绕,没关系,我们慢慢的来讲。前面Looper一篇讲到了Looper是用于给线程创建消息
- 简单的实现了一个树的结构,很不完善!后续参考一些其他代码的实现。试图实现叶子存在可变的节点,能够用来解析xml文件。叶子的代码:packag
- java里有数字long来表示大的整数,如果两个数字的范围超过了long,要做加法算法怎么做呢?这个问题在面试中经常碰到,如果之前没有经历的