SpringBoot系列教材 (十七)- CRUD+分页 - Springboot使用Mybatis实现完整的 增删改查 CRUD和分页


步骤1:Mybatis CRUD和分页
步骤2:先运行,看到效果,再学习
步骤3:模仿和排错
步骤4:基于前面的知识点
步骤5:pom.xml
步骤6:PageHelperConfig
步骤7:CategoryMapper
步骤8:CategoryController
步骤9:listCategory.jsp
步骤10:editCategory.jsp
步骤11:重启测试访问

步骤 1 : Mybatis CRUD和分页

这里使用Mybatis来做一个完整的CRUD和分页。 其中分页使用Mybatis 里讲解的PageHelper插件

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

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

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

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

springboot mybatis读取数据库转为json_spring

步骤 3 : 模仿和排错

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

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

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

本知识点基于Springboot 中 Mybatis 的基本用法 进行扩展学习

步骤 5 : pom.xml

增加对PageHelper的支持

<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
 
<groupId>com.how2java</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot</name>
<description>springboot</description>
<packaging>war</packaging>
 
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
 
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
 
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- servlet依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
 
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- tomcat的支持.-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
 
</dependency>    
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>
 
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
 
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
 
<!-- pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
</dependencies>
 
<properties>
<java.version>1.8</java.version>
</properties>
 
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
 
</project>

步骤 6 : PageHelperConfig

注解@Configuration 表示PageHelperConfig 这个类是用来做配置的。
注解@Bean 表示启动PageHelper这个拦截器。

新增加一个包 com.how2java.springboot.config, 然后添加一个类PageHelperConfig ,其中进行PageHelper相关配置。
offsetAsPageNum:设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用.

p.setProperty("offsetAsPageNum", "true");

rowBoundsWithCount:设置为true时,使用RowBounds分页会进行count查询.

p.setProperty("rowBoundsWithCount", "true");

reasonable:启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页。

p.setProperty("reasonable", "true");

注:RowBounds是什么鬼?我也没搞太清楚。。。反正这么复制粘贴就对了 :|

package com.how2java.springboot.config;
 
import java.util.Properties;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.github.pagehelper.PageHelper;
 
@Configuration
public class PageHelperConfig {
 
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}

步骤 7 : CategoryMapper

修改CategoryMapper,增加CRUD方法的支持。 其实就是调用不同的SQL语句。

package com.how2java.springboot.mapper;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
 
import com.how2java.springboot.pojo.Category;
 
@Mapper
public interface CategoryMapper {
 
@Select("select * from category_ ")
List<Category> findAll();
 
@Insert(" insert into category_ ( name ) values (#{name}) ")
public int save(Category category); 
 
@Delete(" delete from category_ where id= #{id} ")
public void delete(int id);
 
@Select("select * from category_ where id= #{id} ")
public Category get(int id);
 
@Update("update category_ set name=#{name} where id=#{id} ")
public int update(Category category); 
 
}

步骤 8 : CategoryController

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

@RequestMapping("/addCategory")
public String listCategory(Category c) throws Exception {
categoryMapper.save(c);
return "redirect:listCategory";
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category c) throws Exception {
categoryMapper.delete(c.getId());
return "redirect:listCategory";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category c) throws Exception {
categoryMapper.update(c);
return "redirect:listCategory";
}
@RequestMapping("/editCategory")
public String listCategory(int id,Model m) throws Exception {
Category c= categoryMapper.get(id);
m.addAttribute("c", c);
return "editCategory";
}

修改查询映射

@RequestMapping("/listCategory")
public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throwsException {
PageHelper.startPage(start,size,"id desc");
List<Category> cs=categoryMapper.findAll();
PageInfo<Category> page = new PageInfo<>(cs);
m.addAttribute("page", page);        
return "listCategory";
}

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

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

2. 根据start,size进行分页,并且设置id 倒排序

PageHelper.startPage(start,size,"id desc");

3. 因为PageHelper的作用,这里就会返回当前分页的集合了

List<Category> cs=categoryMapper.findAll();

4. 根据返回的集合,创建PageInfo对象

PageInfo<Category> page = new PageInfo<>(cs);

5. 把PageInfo对象扔进model,以供后续显示

m.addAttribute("page", page);     

6. 跳转到listCategory.jsp

return "listCategory";
package com.how2java.springboot.web;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.how2java.springboot.mapper.CategoryMapper;
import com.how2java.springboot.pojo.Category;
 
@Controller
public class CategoryController {
@Autowired CategoryMapper categoryMapper;
 
@RequestMapping("/addCategory")
public String listCategory(Category c) throws Exception {
categoryMapper.save(c);
return "redirect:listCategory";
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category c) throws Exception {
categoryMapper.delete(c.getId());
return "redirect:listCategory";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category c) throws Exception {
categoryMapper.update(c);
return "redirect:listCategory";
}
@RequestMapping("/editCategory")
public String listCategory(int id,Model m) throws Exception {
Category c= categoryMapper.get(id);
m.addAttribute("c", c);
return "editCategory";
}
 
@RequestMapping("/listCategory")
public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size)throws Exception {
PageHelper.startPage(start,size,"id desc");
List<Category> cs=categoryMapper.findAll();
PageInfo<Category> page = new PageInfo<>(cs);
m.addAttribute("page", page);        
return "listCategory";
}
 
}

步骤 9 : listCategory.jsp

通过page.getList遍历当前页面的Category对象。
在分页的时候通过page.pageNum获取当前页面,page.pages获取总页面数。
注:page.getList会返回一个泛型是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.list}" 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=1">[首  页]</a>
<a href="?start=${page.pageNum-1}">[上一页]</a>
<a href="?start=${page.pageNum+1}">[下一页]</a>
<a href="?start=${page.pages}">[末  页]</a>
</div>
<br>
<form action="addCategory" method="post">
 
name: <input name="name"> <br>
<button type="submit">提交</button>
 
</form>
</div>

步骤 10 : 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>

步骤 11 : 重启测试访问

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

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

springboot mybatis读取数据库转为json_springboot学习_02