springboot对jpa的支持以及与bootstrap的简单增删查改+图片上传

一、jpa是什么

       JPA全称Java Persistence API,是一组用于将数据存入数据库的类和方法的集合。JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。   简单说jpa是jdk对数据库提供的接口,可以自动生成表。

二、springboot对jpa的配置

1、创建springboot项目时勾选jpa配置

springboot对jpa的支持以及与bootstrap的简单增删查改+图片上传_第1张图片

 2、在pom.xml添加依赖


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

3、application.yml配置

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

 4、创建一个实体类

注解:

@Entity

@Table(name="表名")

@Id

@GeneratedValue//主键

@Column(length = 100)//列


import javax.persistence.*;

/**
 * @author 疯子侠
 * @site www.donggua.com
 * @company donggua公司
 * @create 2019-02-22 21:27
 */
@Entity
@Table(name = "t_springboot_person")
public class Person {
    @Id
    @GeneratedValue
    private Integer tid;
    @Column(length = 100)
    private String Pdesc;
    @Column(length = 300)
    private String image_path;
    @Column(length = 10)
    private String sex;
    @Column(length = 100)
    private String name;

    public Integer getTid() {
        return tid;
    }

    public void setTid(Integer tid) {
        this.tid = tid;
    }

    public String getPdesc() {
        return Pdesc;
    }

    public void setPdesc(String pdesc) {
        Pdesc = pdesc;
    }

    public String getImage_path() {
        return image_path;
    }

    public void setImage_path(String image_path) {
        this.image_path = image_path;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

启动类在数据库就会生成一张表和一个序列表

springboot对jpa的支持以及与bootstrap的简单增删查改+图片上传_第2张图片

5、继承JpaRepository<实体类,主键的id类型>, JpaSpecificationExecutor<实体类>就有了增删查改的方法

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface PersonDao extends JpaRepository , JpaSpecificationExecutor {
}

实现类

serviceImpl层:

@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonDao personDao;

    @Override
    public Person save(Person person) {
        //在jpa中,增加和修改都是同一个方法
        return personDao.save(person);
    }

    @Override
    public void deleteById(Integer tid) {//删除
        personDao.deleteById(tid);
    }

    @Override
    public Person findById(Integer tid) {//查单个
        //查单个的方法是findById().get(),若用.getOne()这个方法会报错
        return personDao.findById(tid).get();
    }
    @Override
    public Page listPager(Person person, PageBean pageBean) {
         //jpa的Pageable分页是从0页码开始
        //PageBean.start('当前页',‘当也展示记录数’)
        Pageable pageable = PageRequest.of(pageBean.getPage()-1, pageBean.getRows());
        return personDao.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                if(person != null){
                    if(Stringutil.isNotBlank(person.getName())){
                        predicate.getExpressions().add(criteriaBuilder.like(root.get("name"),"%"+person.getName()+"%"));
                    }
                }
                return predicate;
            }
        },pageable);
    }

  }

 

service层 :

    public Person save(Person person) ;

    public void deleteById(Integer tid);

    public Person findById(Integer tid) ;

    public Page listPager(Person person, PageBean pageBean);

三、springboot+jpa+bootstrap做一个简单的增删查改以及图片上传

pom.xml要添加图片上传的依赖


            commons-fileupload
            commons-fileupload
            1.3.1
        

 application.yml配置添加配置

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

config

springboot内嵌tomcat用配置关联

@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/images/**").addResourceLocations("file:E:/temp/");
        super.addResourceHandlers(registry);
    }
}

 

controller层

@Controller
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;

    @RequestMapping("/listPager")
    public ModelAndView list(Person person, HttpServletRequest request){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        ModelAndView modelAndView = new ModelAndView();
        Page persons = personService.listPager(person, pageBean);
        modelAndView.addObject("persons",persons.getContent());
        pageBean.setTotal(persons.getTotalElements()+"");
        modelAndView.addObject("pageCode", PageUtil.createPageCode(pageBean)/*.replaceAll("<","<").replaceAll(">:",">")*/);
        modelAndView.setViewName("list");
        return modelAndView;
    }


    @RequestMapping("/toEdit")
    public ModelAndView toEdit(Person person){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("edit");
        modelAndView.addObject("sexArr",new String[]{"男","女"});
        if(!(person.getTid() == null || "".equals(person.getTid()))) {
            Person t = personService.findById(person.getTid());
            modelAndView.addObject("person", t);
        }
        return modelAndView;
    }

    @RequestMapping("/add")
    public String add(Person person, MultipartFile image){
        try {
            String diskPath = "E://temp/"+image.getOriginalFilename();
            String serverPath = "http://localhost:8080/springboot/images/"+image.getOriginalFilename();
            if(Stringutil.isNotBlank(image.getOriginalFilename())){
                FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
                person.setImage_path(serverPath);
            }
            personService.save(person);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/person/listPager";
    }


    @RequestMapping("/edit")
    public String edit(Person person, MultipartFile image){
        String diskPath = "E://temp/"+image.getOriginalFilename();
        String serverPath = "http://localhost:8080/springboot/images/"+image.getOriginalFilename();
        if(Stringutil.isNotBlank(image.getOriginalFilename())){
            try {
                FileUtils.copyInputStreamToFile(image.getInputStream(),new File(diskPath));
                person.setImage_path(serverPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        personService.save(person);
        return "redirect:/person/listPager";
    }

    @RequestMapping("/del/{bid}")
    public String del(@PathVariable(value = "bid") Integer bid){
        personService.deleteById(bid);
        return "redirect:/person/listPager";
    }
}

pageBean

public class PageBean {
    private int page = 1;// 页码

    private int rows = 3;// 页大小

    private int total = 0;// 总记录数

    private boolean pagination = true;// 是否分页

    //	保存上次查询的参数
    private Map paramMap;
    //	保存上次查询的url
    private String url;

    public void setRequest(HttpServletRequest request) {
        String page = request.getParameter("page");
        String rows = request.getParameter("offset");
        String pagination = request.getParameter("pagination");
        this.setPage(page);
        this.setRows(rows);
        this.setPagination(pagination);
        this.setUrl(request.getRequestURL().toString());
        this.setParamMap(request.getParameterMap());
    }

    public PageBean() {
        super();
    }

    public Map getParamMap() {
        return paramMap;
    }

    public void setParamMap(Map paramMap) {
        this.paramMap = paramMap;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public void setPage(String page) {
        if(Stringutil.isNotBlank(page)) {
            this.page = Integer.parseInt(page);
        }
    }

    public int getRows() {
        return rows;
    }

    public void setRows(String rows) {
        if(Stringutil.isNotBlank(rows)) {
            this.rows = Integer.parseInt(rows);
        }
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public void setTotal(String total) {
        if(Stringutil.isNotBlank(total)) {
            this.total = Integer.parseInt(total);
        }
    }

    public boolean isPagination() {
        return pagination;
    }

    public void setPagination(boolean pagination) {
        this.pagination = pagination;
    }

    public void setPagination(String pagination) {
        if(Stringutil.isNotBlank(pagination) && "false".equals(pagination)) {
            this.pagination = Boolean.parseBoolean(pagination);
        }
    }

    /**
     * 最大页
     * @return
     */
    public int getMaxPage() {
        int max = this.total/this.rows;
        if(this.total % this.rows !=0) {
            max ++ ;
        }
        return max;
    }

    /**
     * 下一页
     * @return
     */
    public int getNextPage() {
        int nextPage = this.page + 1;
        if(nextPage > this.getMaxPage()) {
            nextPage = this.getMaxPage();
        }
        return nextPage;
    }

    /**
     * 上一页
     * @return
     */
    public int getPreviousPage() {
        int previousPage = this.page -1;
        if(previousPage < 1) {
            previousPage = 1;
        }
        return previousPage;
    }


    /**
     * 获得起始记录的下标
     *
     * @return
     */
    public int getStartIndex() {
        return (this.page - 1) * this.rows;
    }

    @Override
    public String toString() {
        return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
    }
}

 Stingutil

public class Stringutil {
    // 私有的构造方法,保护此类不能在外部实例化
    private Stringutil() {
    }

    /**
     * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
     *
     * @param s
     * @return
     */
    public static boolean isBlank(String s) {
        boolean b = false;
        if (null == s || s.trim().equals("")) {
            b = true;
        }
        return b;
    }

    /**
     * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
     *
     * @param s
     * @return
     */
    public static boolean isNotBlank(String s) {
        return !isBlank(s);
    }
}

PageUtil

public class PageUtil {
    public static String createPageCode(PageBean pageBean) {
        StringBuffer sb = new StringBuffer();
        /*
         * 拼接向后台提交数据的form表单
         * 	注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
         */
        sb.append("
"); sb.append(""); Map parameterMap = pageBean.getParamMap(); if(parameterMap != null && parameterMap.size() > 0) { Set> entrySet = parameterMap.entrySet(); for (Map.Entry entry : entrySet) { if(!"page".equals(entry.getKey())) { String[] values = entry.getValue(); for (String val : values) { sb.append(""); } } } } sb.append(""); if(pageBean.getTotal()==0){ return "未查询到数据"; }else{ sb.append("
  • 首页
  • "); if(pageBean.getPage()>1){ sb.append("
  • 上一页
  • "); }else{ sb.append("
  • 上一页
  • "); } for(int i=pageBean.getPage()-1;i<=pageBean.getPage()+1;i++){ if(i<1||i>pageBean.getMaxPage()){ continue; } if(i==pageBean.getPage()){ sb.append("
  • "+i+"
  • "); }else{ sb.append("
  • "+i+"
  • "); } } if(pageBean.getPage()下一页"); }else{ sb.append("
  • 下一页
  • "); } sb.append("
  • 尾页
  • "); } /* * 给分页条添加与后台交互的js代码 */ sb.append(""); return sb.toString(); } }

    前端代码

    list.html

    
    
    
    
        
        Title
        
        
        
        
        
    
    
    
    书籍名称:
    新增
    ID 头像 姓名 性别 简介 操作
    删除 修改

    edit.html

    
    
    
    
        
        用户编辑界面
    
        
    
    
    
    

    教员名称:
    教员描述:
    单选回显

    运行后的效果

    springboot对jpa的支持以及与bootstrap的简单增删查改+图片上传_第3张图片

    你可能感兴趣的:(springboot对jpa的支持以及与bootstrap的简单增删查改+图片上传)