Springboot使用JPA实现完整的增删改查 CRUD和分页

更多内容,点击了解: https://how2j.cn/k/springboot/springboot-jpa-crud-pagination/1650.html

目录

步骤 1 : CRUD和分页

步骤 2 : 先运行,看到效果,再学习

步骤 3 : 模仿和排错

步骤 4 : 基于前面的知识点

步骤 5 : CategoryController

步骤 6 : listCategory.jsp

步骤 7 : editCategory.jsp

步骤 8 : 重启测试


步骤 1 : CRUD和分页

 JPA 基本用法教程中 学习了JPA的基本运用,可是最后呢,总归还是要搞 CRUD和分页的。 并且借助CRUD和分页对JPA 的常用手法做一个学习。

步骤 2 : 先运行,看到效果,再学习

老规矩,先下载下载区(点击进入)的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。 
访问测试地址:

http://127.0.0.1:8080/listCategory?start=1


注: 启动方式是Springboot特有的,直接运行类:com.how2java.springboot.Application 的主方法。

Springboot使用JPA实现完整的增删改查 CRUD和分页

步骤 3 : 模仿和排错

在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。 
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。 
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。 

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。 
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来 
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程

步骤 4 : 基于前面的知识点

本知识点,在Springboot JPA 基本用法的基础上进行

步骤 5 : CategoryController

为CategoryController添加: 增加、删除、获取、修改映射

@RequestMapping("/addCategory")

public String addCategory(Category c) throws Exception {

    categoryDAO.save(c);

    return "redirect:listCategory";

}

@RequestMapping("/deleteCategory")

public String deleteCategory(Category c) throws Exception {

    categoryDAO.delete(c);

    return "redirect:listCategory";

}

@RequestMapping("/updateCategory")

public String updateCategory(Category c) throws Exception {

    categoryDAO.save(c);

    return "redirect:listCategory";

}

@RequestMapping("/editCategory")

public String editCategory(int id,Model m) throws Exception {

    Category c= categoryDAO.getOne(id);

    m.addAttribute("c", c);

    return "editCategory";

}


值得注意:JPA 新增和修改用的都是save. 它根据实体类的id是否为0来判断是进行增加还是修改

修改查询映射

@RequestMapping("/listCategory")

public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0"intstart,@RequestParam(value = "size", defaultValue = "5"int size) throws Exception {

    start = start<0?0:start;

    Sort sort = new Sort(Sort.Direction.DESC, "id");

    Pageable pageable = new PageRequest(start, size, sort);

    Page<Category> page =categoryDAO.findAll(pageable);

    m.addAttribute("page", page);

    return "listCategory";

}


1. 在参数里接受当前是第几页 start ,以及每页显示多少条数据 size。 默认值分别是0和5。

(Model m,@RequestParam(value = "start", defaultValue = "0"int start,@RequestParam(value = "size", defaultValue = "5"int size)


2. 如果 start 为负,那么修改为0. 这个事情会发生在当前是首页,并点击了上一页的时候

start = start<0?0:start;


3. 设置倒排序

Sort sort = new Sort(Sort.Direction.DESC, "id");


4. 根据start,size和sort创建分页对象

Pageable pageable = new PageRequest(start, size, sort);


5. CategoryDAO根据这个分页对象获取结果page. 

Page<Category> page =categoryDAO.findAll(pageable);


在这个page对象里,不仅包含了分页信息,还包含了数据信息,即有哪些分类数据。 这个可以通过getContent()获取出来。
6. 把page放在"page"属性里,跳转到listCategory.jsp

m.addAttribute("page", page);

return "listCategory";

package com.how2java.springboot.web;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;

import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

 

import com.how2java.springboot.dao.CategoryDAO;

import com.how2java.springboot.pojo.Category;

  

@Controller

public class CategoryController {

    @Autowired CategoryDAO categoryDAO;

     

    @RequestMapping("/listCategory")

     

    public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0"intstart,@RequestParam(value = "size", defaultValue = "5"int size) throws Exception {

        start = start<0?0:start;

         

        Sort sort = new Sort(Sort.Direction.DESC, "id");

        Pageable pageable = new PageRequest(start, size, sort);

        Page<Category> page =categoryDAO.findAll(pageable);

         

        System.out.println(page.getNumber());

        System.out.println(page.getNumberOfElements());

        System.out.println(page.getSize());

        System.out.println(page.getTotalElements());

        System.out.println(page.getTotalPages());

         

        m.addAttribute("page", page);

         

        return "listCategory";

    }

 

    @RequestMapping("/addCategory")

    public String addCategory(Category c) throws Exception {

        categoryDAO.save(c);

        return "redirect:listCategory";

    }

    @RequestMapping("/deleteCategory")

    public String deleteCategory(Category c) throws Exception {

        categoryDAO.delete(c);

        return "redirect:listCategory";

    }

    @RequestMapping("/updateCategory")

    public String updateCategory(Category c) throws Exception {

        categoryDAO.save(c);

        return "redirect:listCategory";

    }

    @RequestMapping("/editCategory")

    public String ediitCategory(int id,Model m) throws Exception {

        Category c= categoryDAO.getOne(id);

        m.addAttribute("c", c);

        return "editCategory";

    }

}

步骤 6 : listCategory.jsp

通过page.getContent遍历当前页面的Category对象。
在分页的时候通过page.number获取当前页面,page.totalPages获取总页面数。
注:page.getContent会返回一个泛型是Category的集合。

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

   

<div align="center">

 

</div>

 

<div style="width:500px;margin:20px auto;text-align: center">

    <table align='center' border='1' cellspacing='0'>

        <tr>

            <td>id</td>

            <td>name</td>

            <td>编辑</td>

            <td>删除</td>

        </tr>

        <c:forEach items="${page.content}" var="c" varStatus="st">

            <tr>

                <td>${c.id}</td>

                <td>${c.name}</td>

                <td><a href="editCategory?id=${c.id}">编辑</a></td>

                <td><a href="deleteCategory?id=${c.id}">删除</a></td>

            </tr>

        </c:forEach>

         

    </table>

    <br>

    <div>

                <a href="?start=0">[首  页]</a>

            <a href="?start=${page.number-1}">[上一页]</a>

            <a href="?start=${page.number+1}">[下一页]</a>

            <a href="?start=${page.totalPages-1}">[末  页]</a>

    </div>

    <br>

    <form action="addCategory" method="post">

     

    name: <input name="name"> <br>

    <button type="submit">提交</button>

     

    </form>

</div>

步骤 7 : editCategory.jsp

修改分类的页面

<%@ page language="java" contentType="text/html; charset=UTF-8"

 pageEncoding="UTF-8" isELIgnored="false"%>

 

<div style="margin:0px auto; width:500px">

 

<form action="updateCategory" method="post">

 

name: <input name="name" value="${c.name}"> <br>

 

<input name="id" type="hidden" value="${c.id}">

<button type="submit">提交</button>

 

</form>

</div>

步骤 8 : 重启测试

因为在pom中增加了新jar的依赖,所以要手动重启,重启后访问测试地址:

http://127.0.0.1:8080/listCategory?start=1


看到如图所示的效果

Springboot使用JPA实现完整的增删改查 CRUD和分页


更多内容,点击了解: https://how2j.cn/k/springboot/springboot-jpa-crud-pagination/1650.html