springboot对JPA的支持
导入相关pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.yml文件配置
spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
实体类
package com.caoluo.springboot.entity;
import lombok.Data;
import javax.persistence.*;
/**
* @author caoluo
* @site
* @company
* @create 2019-11-13 16:21
*/
@Data
@Entity
@Table(name = "t_springboot_book")
public class Hbook {
@Id
@GeneratedValue
private Integer bid;
@Column(length = 100)
private String bname;
@Column
private Float price;
}
会创建一个序列以及t_springboot_book表
dao方法
package com.caoluo.springboot.mapper;
import com.caoluo.springboot.entity.Hbook;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author caoluo
* @site
* @company
* @create 2019-11-13 16:41
*/
public interface HbookDao extends JpaRepository<Hbook,Integer> {
}
controller层
package com.caoluo.springboot.controller;
import com.caoluo.springboot.entity.Hbook;
import com.caoluo.springboot.mapper.HbookDao;
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;
/**
* @author caoluo
* @site
* @company
* @create 2019-11-13 16:43
*/
@RestController
@RequestMapping("/jpa")
public class JapController {
@Autowired
private HbookDao jpaDao;
@RequestMapping("/add")
public String add(Hbook book){
jpaDao.save(book);
return "success";
}
@RequestMapping("/edit")
public String edit(Hbook book){
jpaDao.save(book);
return "success";
}
@RequestMapping("/del")
public String del(Hbook book){
jpaDao.delete(book);
return "success";
}
@RequestMapping("/getOne")
public Hbook getOne(Integer bid){
// 会出现懒加载问题:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
// return jpaDao.getOne(bid);
return jpaDao.findById(bid).get();
}
@RequestMapping("/getAll")
public List<Hbook> getAll(){
return jpaDao.findAll();
}
}
运行:
Springboot+bootstrap界面版之增删改查及图片上传
pom依赖
<mysql.version>5.1.44</mysql.version>
<version>${mysql.version}</version>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
application.yml文件配置
server:
port: 80
servlet:
context-path: /
spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3355/t224?useUnicode=true&characterEncoding=utf8
username: root
password: root
druid:
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
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
web-stat-filter:
enabled: true
url-pattern: /*
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
# 解决图片上传大小限制问题,也可采取配置类
servlet:
multipart:
max-file-size: 20MB
max-request-size: 60MB
Springboot05Application.java
package com.caoluo.springboot03;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@SpringBootApplication
public class Springboot03Application {
public static void main(String[] args) {
SpringApplication.run(Springboot03Application.class, args);
}
}
实体类
package com.caoluo.springboot03.entity;
import lombok.ToString;
import javax.persistence.*;
/**
* @company
* @create 2019-02-20 21:58
*/
@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;
}
}
dao
package com.caoluo.springboot03.dao;
import com.caoluo.springboot03.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* @company
* @create 2019-02-18 11:36
*
* 只要继承JpaRepository,通常所用的增删查改方法都有
* 第一个参数:操作的实体类
* 第二个参数:实体类对应数据表的主键
*
* 要使用高级查询必须继承
* org.springframework.data.jpa.repository.JpaSpecificationExecutor<T>接口
*/
public interface TeacherDao extends JpaRepository<Teacher, Integer>, JpaSpecificationExecutor<Teacher> {
}
TeacherService
package com.caoluo.springboot03.service;
import com.caoluo.springboot03.entity.Teacher;
import com.caoluo.springboot03.utils.PageBean;
import com.caoluo.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 javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
/**
* @author caoluo
* @site
* @company
* @create 2019-11-13 18:51
*/
public interface TeacherService {
public Teacher save(Teacher teacher);
public void deleteById(Integer id) ;
public Teacher findById(Integer id);
public Page<Teacher> listPager(Teacher teacher, PageBean pageBean);
}
TeacherServiceImpl
package com.caoluo.springboot03.service.impl;
import com.caoluo.springboot03.dao.TeacherDao;
import com.caoluo.springboot03.entity.Teacher;
import com.caoluo.springboot03.service.TeacherService;
import com.caoluo.springboot03.utils.PageBean;
import com.caoluo.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 TeacherServiceImpl implements TeacherService {
@Autowired
private TeacherDao teacherDao;
@Override
public Teacher save(Teacher teacher) {
return teacherDao.save(teacher);
}
@Override
public void deleteById(Integer id) {
teacherDao.deleteById(id);
}
@Override
public Teacher findById(Integer id) {
return teacherDao.findById(id).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.caoluo.springboot03.Controller;
import com.caoluo.springboot03.entity.Teacher;
import com.caoluo.springboot03.service.TeacherService;
import com.caoluo.springboot03.utils.PageBean;
import com.caoluo.springboot03.utils.PageUtil;
import com.caoluo.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.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
/**
* @company
* @create 2019-02-20 22:15
*/
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@RequestMapping("/listPager")
public ModelAndView list(Teacher teacher, HttpServletRequest request){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
ModelAndView modelAndView = new ModelAndView();
Page<Teacher> teachers = teacherService.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.setViewName("edit");
modelAndView.addObject("sexArr",new String[]{"男","女"});
if(!(teacher.getTid() == null || "".equals(teacher.getTid()))) {
Teacher t = teacherService.findById(teacher.getTid());
modelAndView.addObject("teacher", t);
}
return modelAndView;
}
@RequestMapping("/add")
public String add(Teacher teacher, MultipartFile image){
try {
String diskPath = "E://temp/"+image.getOriginalFilename();
String serverPath = "/uploadImages/"+image.getOriginalFilename();
if(StringUtils.isNotBlank(image.getOriginalFilename())){
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
}
teacherService.save(teacher);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/teacher/listPager";
}
@RequestMapping("/edit")
public String edit(Teacher teacher, MultipartFile image){
String diskPath = "E://temp/"+image.getOriginalFilename();
String serverPath = "http://localhost:8080/springboot/uploadImages/"+image.getOriginalFilename();
if(StringUtils.isNotBlank(image.getOriginalFilename())){
try {
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
teacher.setImagePath(serverPath);
} catch (IOException e) {
e.printStackTrace();
}
}
teacherService.save(teacher);
return "redirect:/teacher/listPager";
}
@RequestMapping("/del/{bid}")
public String del(@PathVariable(value = "bid") Integer bid){
teacherService.deleteById(bid);
return "redirect:/teacher/listPager";
}
}
MyWebAppConfigurer
package com.caoluo.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);
}
}
前台页面:
<!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>
展示数据
<!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="600px">
<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: 60px;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>
<!--<ul class="pagination pagination-sm">-->
<!--<form id='pageBeanForm' action='http://localhost:8080/springboot/teacher/listPager' method='post'><input type='hidden' name='page'></form>-->
<!--<li><a href='javascript:gotoPage(1)'>首页</a></li>-->
<!--<li class='disabled'><a href='javascript:gotoPage(1)'>上一页</a></li>-->
<!--<li class='active'><a href='#'>1</a></li>-->
<!--<li><a href='javascript:gotoPage(2)'>2</a></li>-->
<!--<li><a href='javascript:gotoPage(2)'>下一页</a></li>-->
<!--<li><a href='javascript:gotoPage(4)'>尾页</a></li>-->
<!--<script type='text/javascript'> function gotoPage(page) { document.getElementById('pageBeanForm').page.value = page; document.getElementById('pageBeanForm').submit(); } function skipPage() { var page = document.getElementById('skipPage').value; if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>4){ alert('请输入1~N的数字'); return; } gotoPage(page); }</script>-->
<!--</ul>-->
</nav>
</body>
</html>