1、springboot之jpa支持
导入相关pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.yml文件配置
下面配置文件,我用到druid连接池与数据库进行交互。
server:
port: 80
servlet:
context-path: /
spring:
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/tb_student?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
jpa:
hibernate:
ddl-auto: update
show-sql: true
自动建表相关代码
package com.lzy.springboot03.entity;
import lombok.Data;
import lombok.ToString;
import sun.awt.SunHints;
import javax.persistence.*;
@Entity
@Table(name = "t_springboot_teacher")
public class Teacher {
@Id // 标识为主键
@GeneratedValue // 自增长
private Integer tid;
@Column(length = 16)
private String tname;
@Column(length = 4)
private String sex;
@Column(length = 100)
private String description;
@Column(length = 200)
private String imagePath;
}
jpa值增删改查
TeacherDao
package com.lzy.springboot03.dao;
import com.lzy.springboot03.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2020-01-03 14:54
*
* 只要继承JpaRepository,通常所用的增删查改方法都有
* 第一个参数:操作的实体类
* 第二个参数:实体类对应数据表的主键
*/
public interface TeacherDao extends JpaRepository<Teacher,Integer> {
}
server 层 impl 层省略
controller层
package com.lzy.springboot03.controller;
import com.lzy.springboot03.dao.TeacherDao;
import com.lzy.springboot03.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TeacherController {
@Autowired
private TeacherDao teacherDao;
/*修改
*增加
* 修改和增加调用的是同一个方法,传来的ID跟数据库进行匹配,有则修改,无则新增
* */
@RequestMapping("/save")
public String save(Teacher teacher){
this.teacherDao.save(teacher);
return "success";
}
/*
删除
*
* */
@RequestMapping("/del")
public String del(Teacher teacher){
this.teacherDao.delete(teacher);
return "del success";
}
/* 查询单个 */
@RequestMapping("/select")
public Teacher selectById(Integer tid){
Teacher teacher2 = this.teacherDao.findById(tid).get();
return teacher2;
}
/*
* 查询所有
* */
@RequestMapping("/selectAll")
public List<Teacher> selectAll(){
List<Teacher> all = this.teacherDao.findAll();
return all;
}
}
查询所有:
查询单个:
2、Springboot+bootstrap界面版之增删改查及图片上传
本次案例采取的是spring data jpa和bootstrap3来完成的
需要的pom依赖
<properties>
<mysql.version>5.1.44</mysql.version>
<druid.version>1.1.10</druid.version>
<commons.version>1.3.1</commons.version>
</properties>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- 文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.version}</version>
</dependency>
application.yml文件配置
server:
port: 80
servlet:
context-path: /
spring:
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/tb_student?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
thymeleaf:
cache: false
jpa:
hibernate:
ddl-auto: update
show-sql: true
# 解决图片上传大小限制问题,也可采取配置类
servlet:
multipart:
max-file-size: 20MB
max-request-size: 60MB
Springboot04Application.java
上传文件映射配置类MyWebAppConfigurer.java
package com.lzy.springboot03.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/uploadImages/**").addResourceLocations("file:E:/temp/");
super.addResourceHandlers(registry);
}
}
工具类:StringUtils
package com.lzy.springboot03.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
/**
* set集合转string
* @param hasPerms
* @return
*/
public static String SetToString(Set hasPerms){
return Arrays.toString(hasPerms.toArray()).replaceAll(" ", "").replace("[", "").replace("]", "");
}
/**
* 转换成模糊查询所需参数
* @param before
* @return
*/
public static String toLikeStr(String before){
return isBlank(before) ? null : "%"+before+"%";
}
/**
* 将图片的服务器访问地址转换为真实存放地址
* @param imgpath 图片访问地址(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
* @param serverDir uploadImage
* @param realDir E:/temp/
* @return
*/
public static String serverPath2realPath(String imgpath, String serverDir, String realDir) {
imgpath = imgpath.substring(imgpath.indexOf(serverDir));
return imgpath.replace(serverDir,realDir);
}
/**
* 过滤掉集合里的空格
* @param list
* @return
*/
public static List<String> filterWhite(List<String> list){
List<String> resultList=new ArrayList<String>();
for(String l:list){
if(isNotBlank(l)){
resultList.add(l);
}
}
return resultList;
}
/**
* 从html中提取纯文本
* @param strHtml
* @return
*/
public static String html2Text(String strHtml) {
String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
return txtcontent;
}
public static void main(String[] args) {
}
}
PageUtil
package com.lzy.springboot03.utils;
import java.util.Map;
import java.util.Set;
/**
* 基于bootstrap3生成分页代码
*/
public class PageUtil {
public static String createPageCode(PageBean pageBean) {
StringBuffer sb = new StringBuffer();
/*
* 拼接向后台提交数据的form表单
* 注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
*/
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
sb.append("<input type='hidden' name='page'>");
Map<String, String[]> parameterMap = pageBean.getParamMap();
if(parameterMap != null && parameterMap.size() > 0) {
Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
for (Map.Entry<String, String[]> entry : entrySet) {
if(!"page".equals(entry.getKey())) {
String[] values = entry.getValue();
for (String val : values) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>");
}
}
}
}
sb.append("</form>");
if(pageBean.getTotal()==0){
return "未查询到数据";
}else{
sb.append("<li><a href='javascript:gotoPage(1)'>首页</a></li>");
if(pageBean.getPage()>1){
sb.append("<li><a href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a></li>");
}else{
sb.append("<li class='disabled'><a href='javascript:gotoPage(1)'>上一页</a></li>");
}
for(int i=pageBean.getPage()-1;i<=pageBean.getPage()+1;i++){
if(i<1||i>pageBean.getMaxPage()){
continue;
}
if(i==pageBean.getPage()){
sb.append("<li class='active'><a href='#'>"+i+"</a></li>");
}else{
sb.append("<li><a href='javascript:gotoPage("+i+")'>"+i+"</a></li>");
}
}
if(pageBean.getPage()<pageBean.getMaxPage()){
sb.append("<li><a href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a></li>");
}else{
sb.append("<li class='disabled'><a href='javascript:gotoPage("+pageBean.getMaxPage()+")'>下一页</a></li>");
}
sb.append("<li><a href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a></li>");
}
/*
* 给分页条添加与后台交互的js代码
*/
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append(" }");
sb.append(" function skipPage() {");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){");
sb.append(" alert('请输入1~N的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append(" }");
sb.append("</script>");
return sb.toString();
}
}
entity
package com.lzy.springboot03.entity;
import lombok.Data;
import lombok.ToString;
import sun.awt.SunHints;
import javax.persistence.*;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2020-01-03 14:32
*/
@Entity
@Table(name = "t_springboot_teacher")
@ToString
public class Teacher {
@Id // 标识为主键
@GeneratedValue // 自增长
private Integer tid;
@Column(length = 16)
private String tname;
@Column(length = 4)
private String sex;
@Column(length = 100)
private String description;
@Column(length = 200)
private String imagePath;
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
TeacherDao
package com.lzy.springboot03.dao;
import com.lzy.springboot03.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2020-01-03 14:54
*
* 只要继承JpaRepository,通常所用的增删查改方法都有
* 第一个参数:操作的实体类
* 第二个参数:实体类对应数据表的主键
*
* 要使用高级查询必须继承
* * org.springframework.data.jpa.repository.JpaSpecificationExecutor<T>接口
*/
public interface TeacherDao extends JpaRepository<Teacher,Integer> , JpaSpecificationExecutor<Teacher> {
}
server
package com.lzy.springboot03.server;
import com.lzy.springboot03.dao.TeacherDao;
import com.lzy.springboot03.entity.Teacher;
import com.lzy.springboot03.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
/**
* @author xhy
* @site www.4399.com
* @company xxx公司
* @create 2020-01-03 16:54
*/
public interface TeacherServer {
/* 增加修改*/
Teacher save(Teacher teacher);
void deleteById(Integer tid);
Teacher findById(Integer tid);
Page<Teacher> listPager(Teacher teacher, PageBean pageBean);
}
serverImpl
package com.lzy.springboot03.server.impl;
import com.lzy.springboot03.dao.TeacherDao;
import com.lzy.springboot03.entity.Teacher;
import com.lzy.springboot03.server.TeacherServer;
import com.lzy.springboot03.utils.PageBean;
import com.lzy.springboot03.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
@Service
public class TeacherServerImpl implements TeacherServer {
@Autowired
private TeacherDao teacherDao;
@Override
public Teacher save(Teacher teacher) {
return this.teacherDao.save(teacher);
}
@Override
public void deleteById(Integer tid) {
this.teacherDao.deleteById(tid);
}
@Override
public Teacher findById(Integer tid) {
return this.teacherDao.findById(tid).get();
}
@Override
public Page<Teacher> listPager(Teacher teacher, PageBean pageBean) {
// jpa的Pageable分页是从0页码开始
Pageable pageable = PageRequest.of(pageBean.getPage()-1, pageBean.getRows());
return teacherDao.findAll(new Specification<Teacher>() {
@Override
public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
Predicate predicate = criteriaBuilder.conjunction();
if(teacher != null){
if(StringUtils.isNotBlank(teacher.getTname())){
predicate.getExpressions().add(criteriaBuilder.like(root.get("tname"),"%"+teacher.getTname()+"%"));
}
}
return predicate;
}
},pageable);
}
}
TeacherController
package com.lzy.springboot03.controller;
import com.lzy.springboot03.dao.TeacherDao;
import com.lzy.springboot03.entity.Teacher;
import com.lzy.springboot03.server.TeacherServer;
import com.lzy.springboot03.utils.PageBean;
import com.lzy.springboot03.utils.PageUtil;
import com.lzy.springboot03.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherServer teacherServer;
@RequestMapping("/listPager")
public ModelAndView list(Teacher teacher , HttpServletRequest request){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
ModelAndView modelAndView = new ModelAndView();
Page<Teacher> teachers = this.teacherServer.listPager(teacher, pageBean);
modelAndView.addObject("teachers",teachers.getContent());
pageBean.setTotal(teachers.getTotalElements()+"");
modelAndView.addObject("pageCode", PageUtil.createPageCode(pageBean)/*.replaceAll("<","<").replaceAll(">:",">")*/);
modelAndView.setViewName("list");
return modelAndView;
}
@RequestMapping("/toEdit")
public ModelAndView toEdit(Teacher teacher){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("sexArr",new String[]{"男","女"} );
if(!(teacher.getTid()==null || "".equals(teacher.getTid()))){
Teacher t = teacherServer.findById(teacher.getTid());
modelAndView.addObject("teacher", t);
}
modelAndView.setViewName("edit");
return modelAndView;
}
@RequestMapping("/add")
public String add(Teacher teacher , MultipartFile image){
try {
String diskPath = "E:/jpa/"+image.getOriginalFilename();
String serverPath="/uploadImages/"+image.getOriginalFilename();
if(StringUtils.isNotBlank(image.getOriginalFilename())){
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
}
this.teacherServer.save(teacher);
}catch (Exception e){
e.printStackTrace();
}
return "redirect:/teacher/listPager";
}
@RequestMapping("/edit")
public String edit(Teacher teacher, MultipartFile image){
String diskPath = "E://temp/"+image.getOriginalFilename();
String serverPath = "/uploadImages/"+image.getOriginalFilename();
if(StringUtils.isNotBlank(image.getOriginalFilename())){
try {
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
} catch (IOException e) {
e.printStackTrace();
}
}
teacherServer.save(teacher);
return "redirect:/teacher/listPager";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable(value = "bid") Integer bid){
teacherServer.deleteById(bid);
return "redirect:/teacher/listPager";
}
}
前端页面:
list.jsp
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>书籍列表</title>
<script type="text/javascript" th:src="@{/static/js/xxx.js}"></script>
<link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap-theme.min.css}">
<script type="text/javascript" th:src="@{/static/js/bootstrap3/js/jquery-1.11.2.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/bootstrap3/js/bootstrap.min.js}"></script>
</head>
<body>
<form th:action="@{/teacher/listPager}" method="post">
书籍名称: <input type="text" name="tname" />
<input type="submit" value="提交"/>
</form>
<a th:href="@{/teacher/toEdit}">新增</a>
<table border="1px" width="70%">
<thead>
<tr>
<td>ID</td>
<td>头像</td>
<td>姓名</td>
<td>性别</td>
<td>简介</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr th:each="teacher : ${teachers}">
<td th:text="${teacher.tid}"></td>
<td><img style="width: 200px;height: 60px;" id="imgshow" th:src="${teacher.imagePath}" th:alt="${teacher.tname}"/></td>
<!--<td th:text="${teacher.imagePath}"></td>-->
<td th:text="${teacher.tname}"></td>
<td th:text="${teacher.sex}"></td>
<td th:text="${teacher.description}"></td>
<td>
<a th:href="@{'/teacher/del/'+${teacher.tid}}">删除</a>
<a th:href="@{'/teacher/toEdit?tid='+${teacher.tid}}">修改</a>
</td>
</tr>
</tbody>
</table>
<nav>
<ul class="pagination pagination-sm" th:utext="${pageCode}">
</ul>
</nav>
</body>
</html>
edit.jsp
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户编辑界面</title>
<script type="text/javascript">
function preShow() {
}
</script>
</head>
<body>
<form th:action="@{${teacher.tid} ? '/teacher/edit' : '/teacher/add'}" method="post" enctype="multipart/form-data">
<input type="hidden" name="tid" th:value="${teacher.tid}" />
<input type="hidden" name="imagePath" th:value="${teacher.imagePath}" />
<img id="imgshow" src="" alt=""/>
<input type="file" name="image" onchange="preShow();"></br>
教员名称: <input type="text" name="tname" th:value="${teacher.tname}" /></br>
教员描述: <input type="text" name="description" th:value="${teacher.description}" /></br>
单选回显
<input type="radio" name="sex"
th:each ="s:${sexArr}"
th:value="${s}"
th:text ="${s}"
th:attr ="checked=${s == teacher.sex}">
<input type="submit" value="提交"/>
</form>
</body>
</html>