springboot对JPA的支持

Posted Me*源

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot对JPA的支持相关的知识,希望对你有一定的参考价值。

目标

1springbootjpa支持

2Springboot+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 jpabootstrap3来完成的,

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

工程创建

导入相关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) * 带有分页和排序的 Spring Boot JPA 规范 API

springboot之jpa的支持

springboot官方为何不支持mybatis,而选择底层为hibernate的JPA?

SpringBoot数据访问 SpringBoot整合JPA

springboot之jpa支持

jpa 查询中不支持 DateAdd 函数