springboot集成jpa及图片上传+crud

java1234

共 7811字,需浏览 16分钟

 ·

2020-12-08 18:22

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

66套java从入门到精通实战课程分享

springboot集成jpa

初始化springboot项目时添加jpa组件

如果不选择的话,也可以手动导入pom依赖


      org.springframework.boot
      spring-boot-starter-data-jpa


yml配置

spring:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

自动建表相关代码

package com.xiaoyang.springbootjpa.entity;

import lombok.Data;

import javax.persistence.*;

/**
 * @author xiaoyang
 * @create  2020-12-02 19:23
 */
@Data
@Table(name = "x_springboot_book_2020")
@Entity
public class Book {
    @Id
    @GeneratedValue
    private Integer bid;

    @Column(length = 100)
    private String bname;

    @Column
    private Float price;
}


@Table为表名
运行项目后会将新建表(存在此表会覆盖)包括一张序列表

jpa值增删改查

package com.xiaoyang.springbootjpa.repository;

import com.xiaoyang.springbootjpa.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * @author xiaoyang
 * @create  2020-12-02 19:37
 *  只要继承JpaRepository,通常所用的增删查改方法都有
 *  第一个参数:操作的实体类
 *  第二个参数:实体类对应数据表的主键
 */
@Repository
public interface BookRepository extends JpaRepository {
}


controller层

package com.xiaoyang.springbootjpa.controller;

import com.xiaoyang.springbootjpa.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author xiaoyang
 * @create  2020-12-02 19:57
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Qualifier("bookRepository")
    @Autowired
    private JpaRepository jpaDao;

    @RequestMapping("/add")
    public String add(Book book){
        jpaDao.save(book);
        return "success";
    }

    @RequestMapping("/edit")
    public String edit(Book book){
        jpaDao.save(book);
        return "success";
    }

    @RequestMapping("/del")
    public String del(Book book){
        jpaDao.delete(book);
        return "success";
    }

    @RequestMapping("/getOne")
    public Book getOne(Integer bid){
//        会出现懒加载问题:org.hibernate.LazyInitializationException: could not initialize proxy - no Session
//        return jpaDao.getOne(bid);
        return (Book)jpaDao.findById(bid).get();
    }

    @RequestMapping("/getAll")
    public List getAll(){
        return jpaDao.findAll();
    }
}


复杂查询

package com.xiaoyang.springbootjpa.controller;

import com.xiaoyang.springbootjpa.entity.Teacher;
import com.xiaoyang.springbootjpa.service.TeacherService;
import com.xiaoyang.springbootjpa.utils.PageBean;
import com.xiaoyang.springbootjpa.utils.PageUtil;
import com.xiaoyang.springbootjpa.utils.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;

/**
 * @author xiaoyang
 * @create  2020-12-3 10:00
 */
@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 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";
    }
}

图片上传

pom依赖


        
            commons-fileupload
            commons-fileupload
            1.3.1
        


yml配置

# 解决图片上传大小限制问题,也可采取配置类
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 60MB

映射配置类MyWebAppConfigurer

package com.xiaoyang.springbootjpa.config;

/**
 * @author xiaoyang
 * @create  2020-12-03 9:12
 */

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);
    }
}


controller:

 @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";
    }


over…




版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:

https://blog.csdn.net/qq_45510899/article/details/110524672




粉丝福利:实战springboot+CAS单点登录系统视频教程免费领取

???

?长按上方微信二维码 2 秒
即可获取资料



感谢点赞支持下哈 

浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报