• springboot对JPA的支持


    springbootjpa支持

    导入相关pom依赖

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

    配置application.yml文件

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

    自动建表相关代码

     1 @Entity
     2 @Table(name = "t_springboot_2019")
     3 public class Book {
     4     @Id
     5     @GeneratedValue
     6     private Integer bid;
     7     @Column(length = 100)
     8     private String bname;
     9     @Column
    10     private Float price;

    自动在数据库建一个

    t_springboot_book表

    jpa值增删改查

    只要继承JpaRepository,通常所用的增删查改方法都有

    第一个参数:操作的实体类
     第二个参数:实体类对应数据表的主键

     1 package com.javaqi.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 @Repository
     9 public interface BookRepository extends JpaRepository<Book, Integer> {
    10 }

    controller

    BookController 
     1 package com.javaqi.springboot03.controller;
     2 
     3 import com.javaqi.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 jpabootstrap3来完成

    pom依赖

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     4     <modelVersion>4.0.0</modelVersion>
     5     <parent>
     6         <groupId>org.springframework.boot</groupId>
     7         <artifactId>spring-boot-starter-parent</artifactId>
     8         <version>2.2.1.RELEASE</version>
     9         <relativePath/> <!-- lookup parent from repository -->
    10     </parent>
    11     <groupId>com.javaqi</groupId>
    12     <artifactId>springboot03</artifactId>
    13     <version>0.0.1-SNAPSHOT</version>
    14     <name>springboot03</name>
    15     <description>Demo project for Spring Boot</description>
    16 
    17     <properties>
    18         <java.version>1.8</java.version>
    19         <mysql.version>5.1.44</mysql.version>
    20     </properties>
    21 
    22     <dependencies>
    23         <dependency>
    24             <groupId>org.springframework.boot</groupId>
    25             <artifactId>spring-boot-starter-data-jpa</artifactId>
    26         </dependency>
    27         <dependency>
    28             <groupId>org.springframework.boot</groupId>
    29             <artifactId>spring-boot-starter-jdbc</artifactId>
    30         </dependency>
    31         <dependency>
    32             <groupId>org.springframework.boot</groupId>
    33             <artifactId>spring-boot-starter-thymeleaf</artifactId>
    34         </dependency>
    35         <dependency>
    36             <groupId>org.springframework.boot</groupId>
    37             <artifactId>spring-boot-starter-web</artifactId>
    38         </dependency>
    39 
    40         <dependency>
    41             <groupId>mysql</groupId>
    42             <artifactId>mysql-connector-java</artifactId>
    43             <version>${mysql.version}</version>
    44             <scope>runtime</scope>
    45         </dependency>
    46         <dependency>
    47             <groupId>org.projectlombok</groupId>
    48             <artifactId>lombok</artifactId>
    49             <optional>true</optional>
    50         </dependency>
    51         <dependency>
    52             <groupId>org.springframework.boot</groupId>
    53             <artifactId>spring-boot-starter-test</artifactId>
    54             <scope>test</scope>
    55             <exclusions>
    56                 <exclusion>
    57                     <groupId>org.junit.vintage</groupId>
    58                     <artifactId>junit-vintage-engine</artifactId>
    59                 </exclusion>
    60             </exclusions>
    61         </dependency>
    62 
    63         <dependency>
    64             <groupId>com.alibaba</groupId>
    65             <artifactId>druid-spring-boot-starter</artifactId>
    66             <version>1.1.10</version>
    67         </dependency>
    68 
    69         <dependency>
    70             <groupId>commons-fileupload</groupId>
    71             <artifactId>commons-fileupload</artifactId>
    72             <version>1.3.1</version>
    73         </dependency>
    74     </dependencies>
    75 
    76     <build>
    77         <plugins>
    78             <plugin>
    79                 <groupId>org.springframework.boot</groupId>
    80                 <artifactId>spring-boot-maven-plugin</artifactId>
    81             </plugin>
    82         </plugins>
    83     </build>
    84 
    85 </project>

    配置application.yml

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

    配置Springboot03Application

     1 package com.javaqi.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.javaqi.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  * @author XuFanQi
     9  * @site
    10  * @company
    11  * @create 2019-11-30 17:02
    12  */
    13 @Configuration
    14 public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
    15     @Override
    16     protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    17         registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    18         registry.addResourceHandler("/uploadImages/**").addResourceLocations("file:E:/temp/");
    19         super.addResourceHandlers(registry);
    20     }
    21 }

    StringUtils

     1 package com.javaqi.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*|	|
    |
    </a>", "");//去除字符串中的空格,回车,换行符,制表符
    90         return txtcontent;
    91     }
    92 
    93     public static void main(String[] args) {
    94     }
    95 }

    PageUtil

     1 package com.javaqi.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 }

    PageBean

      1 package com.javaqi.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 }

    实体类(自动生成数据库表)

     1 package com.javaqi.springboot03.entity;
     2 
     3 import lombok.ToString;
     4 
     5 import javax.persistence.*;
     6 
     7 @Entity
     8 @Table(name = "t_springboot_teacher")
     9 @ToString
    10 public class Teacher {
    11     @Id
    12     @GeneratedValue
    13     private Integer tid;
    14     @Column(length = 16)
    15     private String tname;
    16     @Column(length = 4)
    17     private String sex;
    18     @Column(length = 100)
    19     private String description;
    20     @Column(length = 200)
    21     private String imagePath;
    22 
    23     public Integer getTid() {
    24         return tid;
    25     }
    26 
    27     public void setTid(Integer tid) {
    28         this.tid = tid;
    29     }
    30 
    31     public String getTname() {
    32         return tname;
    33     }
    34 
    35     public void setTname(String tname) {
    36         this.tname = tname;
    37     }
    38 
    39     public String getSex() {
    40         return sex;
    41     }
    42 
    43     public void setSex(String sex) {
    44         this.sex = sex;
    45     }
    46 
    47     public String getDescription() {
    48         return description;
    49     }
    50 
    51     public void setDescription(String description) {
    52         this.description = description;
    53     }
    54 
    55     public String getImagePath() {
    56         return imagePath;
    57     }
    58 
    59     public void setImagePath(String imagePath) {
    60         this.imagePath = imagePath;
    61     }
    62 }
    dao层
     1 package com.javaqi.springboot03.repository;
     2 
     3 import com.javaqi.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层 
    TeacherService
     1 package com.javaqi.springboot03.service;
     2 
     3 import com.javaqi.springboot03.entity.Teacher;
     4 import com.javaqi.springboot03.utils.PageBean;
     5 import org.springframework.data.domain.Page;
     6 
     7 /**
     8  * @author XuFanQi
     9  * @site
    10  * @company
    11  * @create 2019-12-01 10:41
    12  */
    13 public interface TeacherService {
    14     public Teacher save(Teacher teacher);
    15     public void deleteById(Integer id);
    16     public Teacher findById(Integer id);
    17     public Page<Teacher> listPager(Teacher teacher, PageBean pageBean);
    18 }
    TeacherServiceImpl 
     1 package com.javaqi.springboot03.service.impl;
     2 
     3 import com.javaqi.springboot03.entity.Teacher;
     4 import com.javaqi.springboot03.repository.TeacherDao;
     5 import com.javaqi.springboot03.service.TeacherService;
     6 import com.javaqi.springboot03.utils.PageBean;
     7 import com.javaqi.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 
    20 /**
    21  * @author XuFanQi
    22  * @site
    23  * @company
    24  * @create 2019-12-01 10:43
    25  */
    26 @Service
    27 public class TeacherServiceImpl implements TeacherService {
    28     @Autowired
    29     private TeacherDao teacherDao;
    30     @Override
    31     public Teacher save(Teacher teacher) {
    32         return teacherDao.save(teacher);
    33     }
    34 
    35     @Override
    36     public void deleteById(Integer id) {
    37         teacherDao.deleteById(id);
    38     }
    39 
    40     @Override
    41     public Teacher findById(Integer id) {
    42         return teacherDao.findById(id).get();
    43     }
    44 
    45     @Override
    46     public Page<Teacher> listPager(Teacher teacher, PageBean pageBean) {
    47 //        jpa的Pageable分页是从0页码开始
    48         Pageable pageable = PageRequest.of(pageBean.getPage()-1, pageBean.getRows());
    49         return teacherDao.findAll(new Specification<Teacher>() {
    50             @Override
    51             public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
    52                 Predicate predicate = criteriaBuilder.conjunction();
    53                 if(teacher != null){
    54                     if(StringUtils.isNotBlank(teacher.getTname())){
    55                         predicate.getExpressions().add(criteriaBuilder.like(root.get("tname"),"%"+teacher.getTname()+"%"));
    56                     }
    57                 }
    58                 return predicate;
    59             }
    60         },pageable);
    61     }
    62 }

    controller层

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

    templates层

    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=" 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>

    浏览器访问结果

    新增,查询,分页

     

     

  • 相关阅读:
    C++笔记(1):使用STL中sort()对struct排序
    Reading papers_13(gesture recognition survey,ing...)
    PCA算法学习_2(PCA理论的matlab实现)
    一些知识点的初步理解_8(Graph Cuts,ing...)
    基础学习笔记之opencv(18):kmeans函数使用实例
    opencv源码解析之(7):CvAdaptiveSkinDetectorl类
    Kinect+OpenNI学习笔记之11(OpenNI驱动kinect手势相关的类的设计)
    基础学习笔记之opencv(22):learning OpenCV书中一个连通域处理函数
    Reading papers_15(Graph cuts optimization for multilimb human segmentation in depth maps)
    Kinect+OpenNI学习笔记之12(简单手势所表示的数字的识别)
  • 原文地址:https://www.cnblogs.com/xcn123/p/11965566.html
Copyright © 2020-2023  润新知