springboot对JPA的支持

目标

1、springboot之jpa支持

2、Springboot+bootstrap界面版之增删改查及图片上传

spring boot之jpa支持

导入pom依赖

1 <dependency>
2             <groupId>org.springframework.boot</groupId>
3             <artifactId>spring-boot-starter-data-jpa</artifactId>
4         </dependency>

配置application.yml信息

1 spring:
2   jpa:
3     hibernate:
4       ddl-auto: update
5     show-sql: true

自动建表代码

 1 package com.yuan.springboot03.entity;
 2
 3 import lombok.Data;
 4
 5 import javax.persistence.*;
 6
 7 @Data
 8 @Table(name = "t_springboot_book_yuan")
 9 @Entity
10 public class Book {
11     @Id
12     @GeneratedValue
13     private Integer bid;
14     @Column(length = 100)
15     private String bname;
16     @Column
17     private Float price;
18
19 }

建表成功

jpa值增删改查

 1 package com.yuan.springboot03.repository;
 2
 3 import com.yuan.springboot03.entity.Book;
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.stereotype.Repository;
 6
 7 /*
 8  * 只要继承JpaRepository,通常所用的增删查改方法都有
 9  *  第一个参数:操作的实体类
10  *  第二个参数:实体类对应数据表的主键
11  */
12
13 @Repository
14 public interface BookRepository extends JpaRepository<Book, Integer> {
15 }

controller层

 1 package com.yuan.springboot03.controller;
 2
 3 import com.yuan.springboot03.entity.Book;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.data.jpa.repository.JpaRepository;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8
 9 import java.util.List;
10
11 @RestController
12 @RequestMapping("/book")
13 public class BookController {
14     @Autowired
15     private JpaRepository jpaDao;
16
17     @RequestMapping("/add")
18     public String add(Book book){
19         jpaDao.save(book);
20         return "success";
21     }
22
23     @RequestMapping("/edit")
24     public String edit(Book book){
25         jpaDao.save(book);
26         return "success";
27     }
28
29     @RequestMapping("/del")
30     public String del(Book book){
31         jpaDao.delete(book);
32         return "success";
33     }
34
35     @RequestMapping("/getOne")
36     public Book getOne(Integer bid){
37 //        会出现懒加载问题:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
38 //        return jpaDao.getOne(bid);
39         return (Book)jpaDao.findById(bid).get();
40     }
41
42     @RequestMapping("/getAll")
43     public List<Book> getAll(){
44         return jpaDao.findAll();
45     }
46 }

查询效果

Springboot+bootstrap界面版之增删改查及图片上传

本次案例采取的是spring data jpa和bootstrap3来完成的,

并没有使用github提供的分页插件Pagehelper,pagehelper与SSM配合分页在前面博客已经有所讲解。

工程创建

导入相关pom依赖

 1 <mysql.version>5.1.44</mysql.version>
 2 <version>${mysql.version}</version>
 3
 4
 5 <dependency>
 6     <groupId>com.alibaba</groupId>
 7     <artifactId>druid-spring-boot-starter</artifactId>
 8     <version>1.1.10</version>
 9 </dependency>
10 <dependency>
11     <groupId>commons-fileupload</groupId>
12     <artifactId>commons-fileupload</artifactId>
13     <version>1.3.1</version>
14 </dependency>
15
16 <dependency>
17     <groupId>org.springframework</groupId>
18     <artifactId>spring-aspects</artifactId>
19 </dependency>

配置application.yml

 1 server:
 2   servlet:
 3     context-path: /springboot
 4 spring:
 5   jpa:
 6     hibernate:
 7       ddl-auto: update
 8     show-sql: true
 9   datasource:
10     type: com.alibaba.druid.pool.DruidDataSource
11     driver-class-name: com.mysql.jdbc.Driver
12     url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=utf8
13     username: mybatis_ssm
14     password: xiaoli
15     druid:
16       initial-size: 5
17       min-idle: 5
18       max-active: 20
19       max-wait: 60000
20       time-between-eviction-runs-millis: 60000
21       min-evictable-idle-time-millis: 30000
22       validation-query: SELECT 1 FROM DUAL
23       test-while-idle: true
24       test-on-borrow: true
25       test-on-return: false
26       pool-prepared-statements: true
27       max-pool-prepared-statement-per-connection-size: 20
28       filter:
29         stat:
30           merge-sql: true
31           slow-sql-millis: 5000
32       web-stat-filter:
33         enabled: true
34         url-pattern: /*
35         exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
36         session-stat-enable: true
37         session-stat-max-count: 100
38       stat-view-servlet:
39         enabled: true
40         url-pattern: /druid/*
41         reset-enable: true
42         login-username: admin
43         login-password: admin
44         allow: 127.0.0.1
45   thymeleaf:
46     cache: false
47
48 # 解决图片上传大小限制问题,也可采取配置类
49   servlet:
50     multipart:
51       max-file-size: 20MB
52       max-request-size: 60MB

Springboot03Application

 1 package com.yuan.springboot03;
 2
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.transaction.annotation.EnableTransactionManagement;
 6
 7 @EnableTransactionManagement
 8 @SpringBootApplication
 9 public class Springboot03Application {
10
11     public static void main(String[] args) {
12         SpringApplication.run(Springboot03Application.class, args);
13     }
14
15 }

上传文件映射配置类MyWebAppConfigurer.java

 1 package com.yuan.springboot03.config;
 2
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 6
 7 /**
 8  * 资源映射路径
 9  */
10 @Configuration
11 public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
12     @Override
13     protected void addResourceHandlers(ResourceHandlerRegistry registry) {
14         registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
15         registry.addResourceHandler("/uploadImages/**").addResourceLocations("file:E:/temp/");
16         super.addResourceHandlers(registry);
17     }
18 }

后台代码

StringUtils

 1 package com.yuan.springboot03.utils;
 2
 3 import java.util.ArrayList;
 4 import java.util.Arrays;
 5 import java.util.List;
 6 import java.util.Set;
 7
 8 public class StringUtils {
 9     // 私有的构造方法,保护此类不能在外部实例化
10     private StringUtils() {
11     }
12
13     /**
14      * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
15      *
16      * @param s
17      * @return
18      */
19     public static boolean isBlank(String s) {
20         boolean b = false;
21         if (null == s || s.trim().equals("")) {
22             b = true;
23         }
24         return b;
25     }
26
27     /**
28      * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
29      *
30      * @param s
31      * @return
32      */
33     public static boolean isNotBlank(String s) {
34         return !isBlank(s);
35     }
36
37     /**
38      * set集合转string
39      * @param hasPerms
40      * @return
41      */
42     public static String SetToString(Set hasPerms){
43         return  Arrays.toString(hasPerms.toArray()).replaceAll(" ", "").replace("[", "").replace("]", "");
44     }
45
46     /**
47      * 转换成模糊查询所需参数
48      * @param before
49      * @return
50      */
51     public static String toLikeStr(String before){
52         return isBlank(before) ? null : "%"+before+"%";
53     }
54
55     /**
56      *    将图片的服务器访问地址转换为真实存放地址
57      * @param imgpath    图片访问地址(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
58      * @param serverDir    uploadImage
59      * @param realDir    E:/temp/
60      * @return
61      */
62     public static String serverPath2realPath(String imgpath, String serverDir, String realDir) {
63         imgpath = imgpath.substring(imgpath.indexOf(serverDir));
64         return imgpath.replace(serverDir,realDir);
65     }
66
67     /**
68      * 过滤掉集合里的空格
69      * @param list
70      * @return
71      */
72     public static List<String> filterWhite(List<String> list){
73         List<String> resultList=new ArrayList<String>();
74         for(String l:list){
75             if(isNotBlank(l)){
76                 resultList.add(l);
77             }
78         }
79         return resultList;
80     }
81
82     /**
83      * 从html中提取纯文本
84      * @param strHtml
85      * @return
86      */
87     public static String html2Text(String strHtml) {
88         String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
89         txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
90         return txtcontent;
91     }
92
93     public static void main(String[] args) {
94     }
95 }

PageBean

  1 package com.yuan.springboot03.utils;
  2
  3 import javax.servlet.http.HttpServletRequest;
  4 import java.util.Map;
  5
  6 /**
  7  * 分页工具类
  8  */
  9 public class PageBean {
 10
 11     private int page = 1;// 页码
 12
 13     private int rows = 3;// 页大小
 14
 15     private int total = 0;// 总记录数
 16
 17     private boolean pagination = true;// 是否分页
 18
 19 //    保存上次查询的参数
 20     private Map<String, String[]> paramMap;
 21 //    保存上次查询的url
 22     private String url;
 23
 24     public void setRequest(HttpServletRequest request) {
 25         String page = request.getParameter("page");
 26         String rows = request.getParameter("offset");
 27         String pagination = request.getParameter("pagination");
 28         this.setPage(page);
 29         this.setRows(rows);
 30         this.setPagination(pagination);
 31         this.setUrl(request.getRequestURL().toString());
 32         this.setParamMap(request.getParameterMap());
 33     }
 34
 35     public PageBean() {
 36         super();
 37     }
 38
 39     public Map<String, String[]> getParamMap() {
 40         return paramMap;
 41     }
 42
 43     public void setParamMap(Map<String, String[]> paramMap) {
 44         this.paramMap = paramMap;
 45     }
 46
 47     public String getUrl() {
 48         return url;
 49     }
 50
 51     public void setUrl(String url) {
 52         this.url = url;
 53     }
 54
 55     public int getPage() {
 56         return page;
 57     }
 58
 59     public void setPage(int page) {
 60         this.page = page;
 61     }
 62
 63     public void setPage(String page) {
 64         if(StringUtils.isNotBlank(page)) {
 65             this.page = Integer.parseInt(page);
 66         }
 67     }
 68
 69     public int getRows() {
 70         return rows;
 71     }
 72
 73     public void setRows(String rows) {
 74         if(StringUtils.isNotBlank(rows)) {
 75             this.rows = Integer.parseInt(rows);
 76         }
 77     }
 78
 79     public int getTotal() {
 80         return total;
 81     }
 82
 83     public void setTotal(int total) {
 84         this.total = total;
 85     }
 86
 87     public void setTotal(String total) {
 88         if(StringUtils.isNotBlank(total)) {
 89             this.total = Integer.parseInt(total);
 90         }
 91     }
 92
 93     public boolean isPagination() {
 94         return pagination;
 95     }
 96
 97     public void setPagination(boolean pagination) {
 98         this.pagination = pagination;
 99     }
100
101     public void setPagination(String pagination) {
102         if(StringUtils.isNotBlank(pagination) && "false".equals(pagination)) {
103             this.pagination = Boolean.parseBoolean(pagination);
104         }
105     }
106
107     /**
108      * 最大页
109      * @return
110      */
111     public int getMaxPage() {
112         int max = this.total/this.rows;
113         if(this.total % this.rows !=0) {
114             max ++ ;
115         }
116         return max;
117     }
118
119     /**
120      * 下一页
121      * @return
122      */
123     public int getNextPage() {
124         int nextPage = this.page + 1;
125         if(nextPage > this.getMaxPage()) {
126             nextPage = this.getMaxPage();
127         }
128         return nextPage;
129     }
130
131     /**
132      * 上一页
133      * @return
134      */
135     public int getPreviousPage() {
136         int previousPage = this.page -1;
137         if(previousPage < 1) {
138             previousPage = 1;
139         }
140         return previousPage;
141     }
142
143
144     /**
145      * 获得起始记录的下标
146      *
147      * @return
148      */
149     public int getStartIndex() {
150         return (this.page - 1) * this.rows;
151     }
152
153     @Override
154     public String toString() {
155         return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
156     }
157 }

PageUtil

 1 package com.yuan.springboot03.utils;
 2
 3 import java.util.Map;
 4 import java.util.Set;
 5
 6 /**
 7  * 基于bootstrap3生成分页代码
 8  */
 9 public class PageUtil {
10     public static String createPageCode(PageBean pageBean) {
11         StringBuffer sb = new StringBuffer();
12         /*
13          * 拼接向后台提交数据的form表单
14          *     注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
15          */
16         sb.append("<form id=‘pageBeanForm‘ action=‘"+pageBean.getUrl()+"‘ method=‘post‘>");
17         sb.append("<input type=‘hidden‘ name=‘page‘>");
18         Map<String, String[]> parameterMap = pageBean.getParamMap();
19         if(parameterMap != null && parameterMap.size() > 0) {
20             Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();
21             for (Map.Entry<String, String[]> entry : entrySet) {
22                 if(!"page".equals(entry.getKey())) {
23                     String[] values = entry.getValue();
24                     for (String val : values) {
25                         sb.append("<input type=‘hidden‘ name=‘"+entry.getKey()+"‘ value=‘"+val+"‘>");
26                     }
27                 }
28             }
29         }
30         sb.append("</form>");
31
32         if(pageBean.getTotal()==0){
33             return "未查询到数据";
34         }else{
35             sb.append("<li><a href=‘javascript:gotoPage(1)‘>首页</a></li>");
36             if(pageBean.getPage()>1){
37                 sb.append("<li><a href=‘javascript:gotoPage("+pageBean.getPreviousPage()+")‘>上一页</a></li>");
38             }else{
39                 sb.append("<li class=‘disabled‘><a href=‘javascript:gotoPage(1)‘>上一页</a></li>");
40             }
41             for(int i=pageBean.getPage()-1;i<=pageBean.getPage()+1;i++){
42                 if(i<1||i>pageBean.getMaxPage()){
43                     continue;
44                 }
45                 if(i==pageBean.getPage()){
46                     sb.append("<li class=‘active‘><a href=‘#‘>"+i+"</a></li>");
47                 }else{
48                     sb.append("<li><a href=‘javascript:gotoPage("+i+")‘>"+i+"</a></li>");
49                 }
50             }
51             if(pageBean.getPage()<pageBean.getMaxPage()){
52                 sb.append("<li><a href=‘javascript:gotoPage("+pageBean.getNextPage()+")‘>下一页</a></li>");
53             }else{
54                 sb.append("<li class=‘disabled‘><a href=‘javascript:gotoPage("+pageBean.getMaxPage()+")‘>下一页</a></li>");
55             }
56             sb.append("<li><a href=‘javascript:gotoPage("+pageBean.getMaxPage()+")‘>尾页</a></li>");
57         }
58
59         /*
60          * 给分页条添加与后台交互的js代码
61          */
62         sb.append("<script type=‘text/javascript‘>");
63         sb.append("        function gotoPage(page) {");
64         sb.append("            document.getElementById(‘pageBeanForm‘).page.value = page;");
65         sb.append("            document.getElementById(‘pageBeanForm‘).submit();");
66         sb.append("        }");
67         sb.append("        function skipPage() {");
68         sb.append("            var page = document.getElementById(‘skipPage‘).value;");
69         sb.append("            if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){");
70         sb.append("                alert(‘请输入1~N的数字‘);");
71         sb.append("                return;");
72         sb.append("            }");
73         sb.append("            gotoPage(page);");
74         sb.append("        }");
75         sb.append("</script>");
76         return sb.toString();
77     }
78 }

实体类entity

 1 package com.yuan.springboot03.entity;
 2
 3 import lombok.ToString;
 4
 5 import javax.persistence.*;
 6
 7 /**
 8  */
 9 @Entity
10 @Table(name = "t_springboot_teacher")
11 @ToString
12 public class Teacher {
13     @Id
14     @GeneratedValue
15     private Integer tid;
16     @Column(length = 16)
17     private String tname;
18     @Column(length = 4)
19     private String sex;
20     @Column(length = 100)
21     private String description;
22     @Column(length = 200)
23     private String imagePath;
24
25     public Integer getTid() {
26         return tid;
27     }
28
29     public void setTid(Integer tid) {
30         this.tid = tid;
31     }
32
33     public String getTname() {
34         return tname;
35     }
36
37     public void setTname(String tname) {
38         this.tname = tname;
39     }
40
41     public String getSex() {
42         return sex;
43     }
44
45     public void setSex(String sex) {
46         this.sex = sex;
47     }
48
49     public String getDescription() {
50         return description;
51     }
52
53     public void setDescription(String description) {
54         this.description = description;
55     }
56
57     public String getImagePath() {
58         return imagePath;
59     }
60
61     public void setImagePath(String imagePath) {
62         this.imagePath = imagePath;
63     }
64 }

dao层

 1 package com.yuan.springboot03.repository;
 2
 3 import com.yuan.springboot03.entity.Teacher;
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 6
 7 /**
 8  * 只要继承JpaRepository,通常所用的增删查改方法都有
 9  *  第一个参数:操作的实体类
10  *  第二个参数:实体类对应数据表的主键
11  *
12  *  要使用高级查询必须继承
13  * org.springframework.data.jpa.repository.JpaSpecificationExecutor<T>接口
14  */
15 public interface TeacherDao extends JpaRepository<Teacher, Integer>, JpaSpecificationExecutor<Teacher> {
16 }

service层及service实现类

 1 package com.yuan.springboot03.service;
 2
 3 import com.yuan.springboot03.entity.Teacher;
 4 import com.yuan.springboot03.utils.PageBean;
 5 import org.springframework.data.domain.Page;
 6
 7 public interface TeacherService {
 8
 9    public Teacher save(Teacher teacher);
10
11     public void deleteById(Integer id);
12
13     public Teacher findById(Integer id);
14
15     public Page<Teacher> listPager(Teacher teacher, PageBean pageBean);
16
17 }
 1 package com.yuan.springboot03.service.impl;
 2
 3 import com.yuan.springboot03.entity.Teacher;
 4 import com.yuan.springboot03.repository.TeacherDao;
 5 import com.yuan.springboot03.service.TeacherService;
 6 import com.yuan.springboot03.utils.PageBean;
 7 import com.yuan.springboot03.utils.StringUtils;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.data.domain.Page;
10 import org.springframework.data.domain.PageRequest;
11 import org.springframework.data.domain.Pageable;
12 import org.springframework.data.jpa.domain.Specification;
13 import org.springframework.stereotype.Service;
14
15 import javax.persistence.criteria.CriteriaBuilder;
16 import javax.persistence.criteria.CriteriaQuery;
17 import javax.persistence.criteria.Predicate;
18 import javax.persistence.criteria.Root;
19 @Service
20 public class TeacherServiceImpl implements TeacherService {
21     @Autowired
22     private TeacherDao teacherDao;
23     @Override
24     public Teacher save(Teacher teacher) {
25         return teacherDao.save(teacher);
26     }
27
28     @Override
29     public void deleteById(Integer id) {
30         teacherDao.deleteById(id);
31     }
32
33     @Override
34     public Teacher findById(Integer id) {
35         return teacherDao.findById(id).get();
36     }
37
38     @Override
39     public Page<Teacher> listPager(Teacher teacher, PageBean pageBean) {
40 //        jpa的Pageable分页是从0页码开始
41         Pageable pageable = PageRequest.of(pageBean.getPage()-1, pageBean.getRows());
42         return teacherDao.findAll(new Specification<Teacher>() {
43             @Override
44             public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
45                 Predicate predicate = criteriaBuilder.conjunction();
46                 if(teacher != null){
47                     if(StringUtils.isNotBlank(teacher.getTname())){
48                         predicate.getExpressions().add(criteriaBuilder.like(root.get("tname"),"%"+teacher.getTname()+"%"));
49                     }
50                 }
51                 return predicate;
52             }
53         },pageable);
54     }
55 }

controller层

 1 package com.yuan.springboot03.controller;
 2
 3 import com.yuan.springboot03.entity.Teacher;
 4 import com.yuan.springboot03.service.TeacherService;
 5 import com.yuan.springboot03.utils.PageBean;
 6 import com.yuan.springboot03.utils.PageUtil;
 7 import com.yuan.springboot03.utils.StringUtils;
 8 import org.apache.commons.io.FileUtils;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.data.domain.Page;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.PathVariable;
13 import org.springframework.web.bind.annotation.RequestMapping;
14 import org.springframework.web.multipart.MultipartFile;
15 import org.springframework.web.servlet.ModelAndView;
16
17 import javax.servlet.http.HttpServletRequest;
18 import java.io.File;
19 import java.io.IOException;
20
21 /**
22  */
23 @Controller
24 @RequestMapping("/teacher")
25 public class TeacherController {
26     @Autowired
27     private TeacherService teacherService;
28
29     @RequestMapping("/listPager")
30     public ModelAndView list(Teacher teacher, HttpServletRequest request){
31         PageBean pageBean = new PageBean();
32         pageBean.setRequest(request);
33         ModelAndView modelAndView = new ModelAndView();
34         Page<Teacher> teachers = teacherService.listPager(teacher, pageBean);
35         modelAndView.addObject("teachers",teachers.getContent());
36         pageBean.setTotal(teachers.getTotalElements()+"");
37         modelAndView.addObject("pageCode", PageUtil.createPageCode(pageBean)/*.replaceAll("<","<").replaceAll("&gt:",">")*/);
38         modelAndView.setViewName("list");
39         return modelAndView;
40     }
41
42     @RequestMapping("/toEdit")
43     public ModelAndView toEdit(Teacher teacher){
44         ModelAndView modelAndView = new ModelAndView();
45         modelAndView.setViewName("edit");
46         modelAndView.addObject("sexArr",new String[]{"男","女"});
47         if(!(teacher.getTid() == null || "".equals(teacher.getTid()))) {
48             Teacher t = teacherService.findById(teacher.getTid());
49             modelAndView.addObject("teacher", t);
50         }
51         return modelAndView;
52     }
53
54     @RequestMapping("/add")
55     public String add(Teacher teacher, MultipartFile image){
56         try {
57             String diskPath = "E://temp/"+image.getOriginalFilename();
58             String serverPath = "/uploadImages/"+image.getOriginalFilename();
59             if(StringUtils.isNotBlank(image.getOriginalFilename())){
60                 FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
61                 teacher.setImagePath(serverPath);
62             }
63             teacherService.save(teacher);
64         } catch (IOException e) {
65             e.printStackTrace();
66         }
67         return "redirect:/teacher/listPager";
68     }
69
70
71     @RequestMapping("/edit")
72     public String edit(Teacher teacher, MultipartFile image){
73         String diskPath = "E://temp/"+image.getOriginalFilename();
74         String serverPath = "/uploadImages/"+image.getOriginalFilename();
75         if(StringUtils.isNotBlank(image.getOriginalFilename())){
76             try {
77                 FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
78                 teacher.setImagePath(serverPath);
79             } catch (IOException e) {
80                 e.printStackTrace();
81             }
82         }
83         teacherService.save(teacher);
84         return "redirect:/teacher/listPager";
85     }
86
87     @RequestMapping("/del/{bid}")
88     public String del(@PathVariable(value = "bid") Integer bid){
89         teacherService.deleteById(bid);
90         return "redirect:/teacher/listPager";
91     }
92 }

页面代码

list.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <html xmlns:th="http://www.thymeleaf.org">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>书籍列表</title>
 7     <script type="text/javascript" th:src="@{/static/js/xxx.js}"></script>
 8     <link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap.min.css}">
 9     <link rel="stylesheet" th:href="@{/static/js/bootstrap3/css/bootstrap-theme.min.css}">
10     <script type="text/javascript" th:src="@{/static/js/bootstrap3/js/jquery-1.11.2.min.js}"></script>
11     <script type="text/javascript" th:src="@{/static/js/bootstrap3/js/bootstrap.min.js}"></script>
12 </head>
13 <body>
14 <form th:action="@{/teacher/listPager}" method="post">
15     书籍名称: <input type="text" name="tname" />
16     <input type="submit" value="提交"/>
17 </form>
18 <a th:href="@{/teacher/toEdit}">新增</a>
19 <table border="1px" width="600px">
20     <thead>
21     <tr>
22         <td>ID</td>
23         <td>头像</td>
24         <td>姓名</td>
25         <td>性别</td>
26         <td>简介</td>
27         <td>操作</td>
28     </tr>
29     </thead>
30     <tbody>
31     <tr th:each="teacher : ${teachers}">
32         <td th:text="${teacher.tid}"></td>
33         <td><img style="width: 60px;height: 60px;" id="imgshow" th:src="${teacher.imagePath}" th:alt="${teacher.tname}"/></td>
34         <!--<td th:text="${teacher.imagePath}"></td>-->
35         <td th:text="${teacher.tname}"></td>
36         <td th:text="${teacher.sex}"></td>
37         <td th:text="${teacher.description}"></td>
38         <td>
39             <a th:href="@{‘/teacher/del/‘+${teacher.tid}}">删除</a>
40             <a th:href="@{‘/teacher/toEdit?tid=‘+${teacher.tid}}">修改</a>
41         </td>
42     </tr>
43     </tbody>
44 </table>
45
46
47 <nav>
48     <ul class="pagination pagination-sm" th:utext="${pageCode}">
49     </ul>
50
51     <!--<ul class="pagination pagination-sm">-->
52     <!--<form id=‘pageBeanForm‘ action=‘http://localhost:8080/springboot/teacher/listPager‘ method=‘post‘><input type=‘hidden‘ name=‘page‘></form>-->
53     <!--<li><a href=‘javascript:gotoPage(1)‘>首页</a></li>-->
54     <!--<li class=‘disabled‘><a href=‘javascript:gotoPage(1)‘>上一页</a></li>-->
55     <!--<li class=‘active‘><a href=‘#‘>1</a></li>-->
56     <!--<li><a href=‘javascript:gotoPage(2)‘>2</a></li>-->
57     <!--<li><a href=‘javascript:gotoPage(2)‘>下一页</a></li>-->
58     <!--<li><a href=‘javascript:gotoPage(4)‘>尾页</a></li>-->
59     <!--<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>-->
60     <!--</ul>-->
61 </nav>
62 </body>
63 </html>

edit.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <html xmlns:th="http://www.thymeleaf.org">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>用户编辑界面</title>
 7
 8     <script type="text/javascript">
 9         function preShow() {
10
11         }
12     </script>
13 </head>
14 <body>
15
16 <form th:action="@{${teacher.tid} ? ‘/teacher/edit‘ : ‘/teacher/add‘}" method="post" enctype="multipart/form-data">
17     <input type="hidden" name="tid" th:value="${teacher.tid}" />
18     <input type="hidden" name="imagePath" th:value="${teacher.imagePath}" />
19     <img id="imgshow" src="" alt=""/>
20     <input type="file" name="image" onchange="preShow();"></br>
21     教员名称: <input type="text" name="tname" th:value="${teacher.tname}" /></br>
22     教员描述: <input type="text" name="description" th:value="${teacher.description}" /></br>
23     单选回显
24     <input type="radio" name="sex"
25            th:each ="s:${sexArr}"
26            th:value="${s}"
27            th:text ="${s}"
28            th:attr ="checked=${s == teacher.sex}">
29
30     <input type="submit" value="提交"/>
31 </form>
32
33 </body>
34 </html>

项目结构

功能实现

分页功能

thymeleaf单选回显,多选回显,下拉选回显,默认选中第一个

 1 //默认选中第一个
 2 <input type ="radio" name="repaymentType"
 3     th:each ="repaymentType,repaymentState:${repaymentTypeList}"
 4     th:value="${repaymentType.dictName}"
 5     th:text ="${repaymentType.dictName}"
 6     th:attr ="checked=${repaymentState.index==0?true:false}">
 7
 8 //单选回显
 9 <input type="radio" name="repaymentType"
10    th:each ="repaymentType:${repaymentTypeList}"
11    th:value="${repaymentType.dictName}"
12    th:text ="${repaymentType.dictName}"
13    th:attr ="checked=${financeProductDO.repaymentType == repaymentType.dictName?true:false}">
14
15 //多选回显
16 <input type ="checkbox" name="companyRole"
17     th:each ="role : ${companyRoleList}"
18     th:value="${role.dictName}"
19     th:text ="${role.dictName}"
20     th:attr ="checked=${companyInformation.companyRole.contains(role.dictName)?true:false}">
21
22 //下拉选回显默认选中 前台接收到参数:user对象和businessList集合
23 <option th:selected="${user.businessId eq busi.businessId}"
24         th:each="busi:${businessList}"
25         th:value="${busi.businessId}"
26         th:text="${busi.businessName}" >
27 </option>

谢谢观看!!!

原文地址:https://www.cnblogs.com/ly-0919/p/11965528.html

时间: 2024-11-09 03:00:39

springboot对JPA的支持的相关文章

springboot之jpa的支持

1.springboot之jpa支持 2.Springboot+bootstrap界面版之增删改查及图片上传 springboot之jpa支持 导入相关pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> application.

springboot使用jpa,删除功能sql报错解决

springboot使用jpa时报错: 只有删除时报错了, "data": "删除失败,原因:Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failur

二、springboot使用jpa

花了几天时间,好好看了看springboot的jpa部分,总结了常用的形式. 1.通过STS工具添加jpa的依赖项 要连mysql,测试的时候需要web,顺便添加了lombok不写set和get方法了. 2.添加配置 application.properties: 要连接mysql.设置jpa的两个参数,一个是更改entity后更新表,还一个是显示sql,为了查错用 添加一个config类,开启jpa,添加扫描repository路径 最后需要建立一个web请求入口,方便调用调试,增加web很简

带你搭一个SpringBoot+SpringData JPA的环境

前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 不知道大家对SpringBoot和Spring Data JPA了解多少,如果你已经学过Spring和Hibernate的话,那么SpringBoot和SpringData JPA可以分分钟上手的.SpringBoot和SpringData JPA的好处我就不说了,当时我学习的时候也粗略做过笔记,有兴趣的同学可以去看看 SpringBoot就是这么简

【极简版】SpringBoot+SpringData JPA 管理系统

前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 在上一篇中已经讲解了如何从零搭建一个SpringBoot+SpringData JPA的环境,测试接口的时候也成功获取得到数据了. 带你搭一个SpringBoot+SpringData JPA的Demo 我的目的是做一个十分简易的管理系统,这就得有页面,下面我继续来讲讲我是怎么快速搭一个管理系统的. ps:由于是简易版,我的目的是能够快速搭建,而不在

用SpringBoot+MySql+JPA实现对数据库的增删改查和分页

使用SpringBoot+Mysql+JPA实现对数据库的增删改查和分页      JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.  使用Springboot和jpa对数据库进行操作时,能够大大减少我们的工作量,在jpa中,已经在底层封装好了增删查的功能和sql语句,可以使我们进行快速开发 项目流程 一.新建一个项目 二.配置文件 #数据源配置 spring.dat

Springboot 使用JPA

Springboot 使用jpa maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId>

【转】【链接】SpringBoot配置SSL同时支持http和https访问

SpringBoot配置SSL同时支持http和https访问:https://blog.csdn.net/qq_38288606/article/details/89478353#comments 原文地址:https://www.cnblogs.com/xiaostudy/p/12358297.html

【SpringBoot】SpringBoot 与JPA整合(十四)

本章介绍SpringBoot与JPA整合 整合流程 1.新建一个SpringBoot Web项目 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:s