目录
前言
JPA是Java Persistence API的简称:中文名Java持久层API
是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
简单的说hibernate就是他的底层。所有的都可以参照hibernate
Jpa能做到的
Jpa的配置文件pom.xml,yml
pom.xml
<!--使用jpa框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
application.yml
jpa:
hibernate:
ddl-auto: update
show-sql: true
1、通过操控java实体类而自动生成数据库表结构
比如说写了这个实体类,不用在数据库建表,在运行过程中他就会自动创建好。
package com.liwangwang.springboot3.entity;
import lombok.ToString;
import javax.persistence.*;
@data
@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;
}
创建之前
创建之后
2、jpa继承JpaRepository后就有一套简单的增删改查
package com.liwangwang.springboot3.dao;
import com.liwangwang.springboot3.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* 只要继承JpaRepository,通常所用的增删查改方法都有
* 第一个参数:操作的实体类
* 第二个参数:实体类对应数据表的主键
*
* 要使用高级查询必须继承
* org.springframework.data.jpa.repository.JpaSpecificationExecutor<T>接口
*/
public interface TeacherDao extends JpaRepository<Teacher, Integer>, JpaSpecificationExecutor<Teacher> {
}
用jpa+bootstarp做一个增删改查和文件上传
重点文件配置
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liwangwang</groupId>
<artifactId>springboot3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot3</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.44</mysql.version>
</properties>
<dependencies>
<!--数据库data的jdbc操作-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!--使用了thymeleaf的模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--管理web请求的配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql的一个驱动,用的版本为5.1.44-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
<scope>runtime</scope>
</dependency>
<!--导入lombok工具,不用写set,get方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--只能在测试test里面进行一个测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--阿里巴巴的一个druid的数据源,以前使用的是dbcp2-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--解决没有@aspect注解的问题-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<!--pagehelper分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!--Redis缓存策略-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!--使用jpa框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
servlet:
context-path: /
port: 80
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:3306/context?useUnicode=true&characterEncoding=utf8
username: root
password: 123
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
重点文件介绍
一个文件上传的配置类MyWebAppConfigurer
没有这个配置类就没办法上传图片了
package com.liwangwang.springboot3.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);
}
}
在控制层控制好图片的存放位置
package com.liwangwang.springboot3.controller;
import com.liwangwang.springboot3.entity.Teacher;
import com.liwangwang.springboot3.service.TeacherService;
import com.liwangwang.springboot3.util.PageBean;
import com.liwangwang.springboot3.util.PageUtil;
import com.liwangwang.springboot3.util.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;
@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 = "/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";
}
}
项目结构和结果图
后记
因为一个jpa文档太多了,所以干脆给项目吧
暂时就放一些重要的代码看看
链接:添加链接描述
提取码:3oy3