springboot的Jpa框架介绍

目录

  • 前言
    • Jpa能做到的
      • Jpa的配置文件pom.xml,yml
      • 1、通过操控java实体类而自动生成数据库表结构
      • 2、jpa继承JpaRepository后就有一套简单的增删改查
    • 用jpa+bootstarp做一个增删改查和文件上传
      • 重点文件配置
        • pom.xml
        • application.yml
      • 重点文件介绍
        • 一个文件上传的配置类MyWebAppConfigurer
        • 在控制层控制好图片的存放位置
      • 项目结构和结果图
  • 后记

前言

JPA是Java Persistence API的简称:中文名Java持久层API
是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

简单的说hibernate就是他的底层。所有的都可以参照hibernate

Jpa能做到的

Jpa的配置文件pom.xml,yml

pom.xml

		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-jpaartifactId>
		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;

   
}

创建之前
springboot的Jpa框架介绍_第1张图片
创建之后
springboot的Jpa框架介绍_第2张图片

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接口
 */
public interface TeacherDao extends JpaRepository<Teacher, Integer>, JpaSpecificationExecutor<Teacher> {
}

用jpa+bootstarp做一个增删改查和文件上传

重点文件配置

pom.xml


<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.0modelVersion>
	<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.2.1.RELEASEversion>
		<relativePath/> 
	parent>
	<groupId>com.liwangwanggroupId>
	<artifactId>springboot3artifactId>
	<version>0.0.1-SNAPSHOTversion>
	<name>springboot3name>
	<description>Demo project for Spring Bootdescription>

	<properties>
		<java.version>1.8java.version>
		<mysql.version>5.1.44mysql.version>
	properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-jdbcartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-thymeleafartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<version>${mysql.version}version>
			<scope>runtimescope>
		dependency>
		
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<optional>trueoptional>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintagegroupId>
					<artifactId>junit-vintage-engineartifactId>
				exclusion>
			exclusions>
		dependency>
		
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>druid-spring-boot-starterartifactId>
			<version>1.1.10version>
		dependency>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-aspectsartifactId>
		dependency>
		
		<dependency>
			<groupId>com.github.pagehelpergroupId>
			<artifactId>pagehelper-spring-boot-starterartifactId>
			<version>1.2.3version>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-redisartifactId>
		dependency>
		<dependency>
			<groupId>redis.clientsgroupId>
			<artifactId>jedisartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-data-jpaartifactId>
		dependency>
		
		<dependency>
			<groupId>commons-fileuploadgroupId>
			<artifactId>commons-fileuploadartifactId>
			<version>1.3.1version>
		dependency>

	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			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";
    }
}

项目结构和结果图

springboot的Jpa框架介绍_第3张图片
springboot的Jpa框架介绍_第4张图片

后记

因为一个jpa文档太多了,所以干脆给项目吧
暂时就放一些重要的代码看看

链接:添加链接描述
提取码:3oy3

你可能感兴趣的:(#,springboot,springboot,jpa)