springboot 增删改查+分页(基于Mybatis注解方式)
步骤一:关于Mybatis
Mybatis 是用来进行数据库操作的框架。其中分页使用Mybatis中的PageHelper插件。
Mybatis与hibernate对比:
1.hibernate是一个完全的orm框架(对象关系映射,对 对象操作 表就会改变),mybatis并不是一个完全的orm框架,只是对sql语句的封装。
2.hibernate,可以不用写sql语句。mybatis就是面向sql语句的,必须写sql语句。但是底层原理都是JDBC。
3.应用场景:
hibernate:应用传统项目,互联网项目中都不用。
mybatis:主要是互联网项目。
步骤二:创建数据库和表
创建个分类表,字段很简单,就id和name。
create database test01;
use test01;
CREATE TABLE category_ (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30),
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
步骤三:准备数据
insert into category_ values(null,'家具');
insert into category_ values(null,'电器');
insert into category_ values(null,'服装');
insert into category_ values(null,'化妆品');
步骤四:基于springboot入门小demo
基于的springboot入门小demo,已包含了前面文章的知识点(比如:热部署、全局异常处理器)。
步骤五:修改application.properties配置文件,连接数据库
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test01?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
步骤六:修改pom.xml文件
增加对mysql和mybatis的支持,及增加对PageHelper的支持(分页)。
<!-- 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>
步骤七:创建PageHelperConfig 分页配置类
注解@Configuration 表示PageHelperConfig 这个类是用来做配置的。
注解@Bean 表示启动PageHelper这个拦截器。
新增加一个包 cn.xdf.springboot.config, 然后添加一个类PageHelperConfig ,其中进行PageHelper相关配置。
package cn.xdf.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();
//1.offsetAsPageNum:设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用.
p.setProperty("offsetAsPageNum", "true");
//2.rowBoundsWithCount:设置为true时,使用RowBounds分页会进行count查询.
p.setProperty("rowBoundsWithCount", "true");
//3.reasonable:启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页。
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
步骤八:创建pojo类Category(不同于JPA的点,不需要映射)
增加一个包:cn.xdf.springboot.pojo,然后创建实体类Category。
package cn.xdf.springboot.pojo;
public class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
步骤九:创建接口CategoryMapper(不同于JPA的点)
增加一个包:cn.xdf.springboot.mapper,然后创建接口CategoryMapper。
使用注解@Mapper 表示这是一个Mybatis Mapper接口。
使用@Select注解表示调用findAll方法会去执行对应的sql语句。再增加CRUD方法的支持。
package cn.xdf.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 cn.xdf.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);
}
步骤十:创建CategoryController (不同于JPA的点--分页)
增加一个包:cn.xdf.springboot.controller,然后创建CategoryController 类。
1. 接受listCategory映射
2. 然后获取所有的分类数据
3. 接着放如Model中
4. 跳转到listCategory.jsp中
5.再为CategoryController添加: 增加、删除、获取、修改映射
package cn.xdf.springboot.controller;
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 cn.xdf.springboot.mapper.CategoryMapper;
import cn.xdf.springboot.pojo.Category;
@Controller
public class CategoryController {
@Autowired
CategoryMapper categoryMapper;
// @RequestMapping("/listCategory")
// public String listCategory(Model m) throws Exception {
// List<Category> cs = categoryMapper.findAll();
// m.addAttribute("cs", cs);
// return "listCategory";
// }
@RequestMapping("/listCategory")
public String listCategory(Model m,@RequestParam(value="start",defaultValue="0")int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
//1. 在参数里接受当前是第几页 start ,以及每页显示多少条数据 size。 默认值分别是0和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";
}
@RequestMapping("/addCategory")
public String addCategory(Category c)throws Exception{
categoryMapper.save(c);
return "redirect:listCategory"; //添加成功,重定向到分类查询页面
}
@RequestMapping("/deleteCategory")
public String deleteCategory(int id)throws Exception{
categoryMapper.delete(id);
return "redirect:listCategory"; //删除成功,重定向到分类查询页面
}
@RequestMapping("/updateCategory") //修改方法
public String updateCategory(Category c)throws Exception{
categoryMapper.update(c);
return "redirect:listCategory"; //修改成功,重定向到分类查询页面
}
@RequestMapping("/editCategory")
public String editCategory(int id ,Model m)throws Exception{
Category c = categoryMapper.get(id); //根据id查询
m.addAttribute("c", c); //查到展示到修改页面
return "editCategory"; //跳转到修改页面
}
}
步骤十一:创建listCategory.jsp (不同于JPA的点--page中参数)
用jstl遍历从CategoryController传递过来的集合:cs。
通过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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>分类展示列表</title>
</head>
<body>
<!-- <table align="center" border="1" > -->
<!-- <tr> -->
<!-- <td>id</td> -->
<!-- <td>name</td> -->
<!-- </tr> -->
<%-- <c:forEach items="${cs}" var="c" varStatus="st"> --%>
<!-- <tr> -->
<%-- <td>${c.id}</td> --%>
<%-- <td>${c.name}</td> --%>
<!-- </tr> -->
<%-- </c:forEach> --%>
<!-- </table> -->
<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> <!-- 这是相对路径的写法。 前面没有斜线就是相对当前路径加上这个地址。 -->
<c:if test="${page.pageNum-1>0}">
<a href="?start=${page.pageNum-1}">[上一页]</a>
</c:if>
<c:if test="${page.pageNum+1<page.pages+1}">
<a href="?start=${page.pageNum+1}">[下一页]</a>
</c:if>
<a href="?start=${page.pages}">[末 页]</a>
</div>
<br>
<div>当前页/总页数:<a href="?start=${page.pageNum}">${page.pageNum}</a>/<a href="?start=${page.pages}">${page.pages}</a> </div>
<br>
<form action="addCategory" method="post">
添加分类:
name: <input name="name"> <br>
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
步骤十二:创建editCategory.jsp
修改分类的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<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>
</body>
</html>
步骤十三:重启测试
因为在pom中增加了新jar的依赖,所以要手动重启,重启后访问测试地址:http://127.0.0.1:8080/listCategory
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL2QTMyEDM3UzMx0SN2UDMxMzM3EjNycDM4EDMy0SOwQDOyMTMvw1NwgTMwIzLclDM0gjMzEzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzcldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
点击下一页: