Spring Boot CRUD+分页(基于Mybatis注解方式)
步骤一:关于Mybatis
Mybatis 是用来进行数据库操作的框架。其中分页使用Mybatis中的PageHelper插件。
Mybatis与hibernate对比:
1.hibernate是一个完全的orm框架(对象关系映射,对 对象操作 表就会改变),mybatis并不是一个完全的orm框架,只是对sql语句的封装。
2.hibernate,可以不用写sql语句。mybatis就是面向sql语句的,必须写sql语句。但是底层原理都是JDBC。
3.应用场景:
hibernate:应用传统项目,互联网项目中都不用。
步骤二:创建数据库和表
创建个分类表,字段很简单,就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
点击下一页:
Spring Boot CRUD+分页(基于Mybatis注解方式)的更多相关文章
- Spring Boot CRUD+分页(基于JPA规范)
步骤一:JPA概念 JPA(Java Persistence API)是Sun官方提出的Java持久化规范,用来方便大家操作数据库. 真正干活的可能是Hibernate,TopLink等等实现了JPA ...
- Spring Boot 框架下使用MyBatis访问数据库之基于XML配置的方式
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML ...
- Spring Boot整合Mybatis(注解方式和XML方式)
其实对我个人而言还是不够熟悉JPA.hibernate,所以觉得这两种框架使用起来好麻烦啊. 一直用的Mybatis作为持久层框架, JPA(Hibernate)主张所有的SQL都用Java代码生成, ...
- spring与hibernate整合配置基于Annotation注解方式管理实务
1.配置数据源 数据库连接基本信息存放到properties文件中,因此先加载properties文件 <!-- jdbc连接信息 --> <context:property-pla ...
- mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类
相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...
- SpringBoot 源码解析 (九)----- Spring Boot的核心能力 - 整合Mybatis
本篇我们在SpringBoot中整合Mybatis这个orm框架,毕竟分析一下其自动配置的源码,我们先来回顾一下以前Spring中是如何整合Mybatis的,大家可以看看我这篇文章Mybaits 源码 ...
- 6、Spring Boot 2.x 集成 MyBatis
1.6 Spring Boot 2.x 集成 MyBatis 简介 详细介绍如何在Spring Boot中整合MyBatis,并通过注解方式实现映射. 完整源码: 1.6.1 创建 spring-bo ...
- 07.深入浅出 Spring Boot - 数据访问之Mybatis(附代码下载)
MyBatis 在Spring Boot应用非常广,非常强大的一个半自动的ORM框架. 代码下载:https://github.com/Jackson0714/study-spring-boot.gi ...
- Spring Boot简化了基于Spring的应用开发
Spring Boot简化了基于Spring的应用开发,通过少量的代码就能创建一个独立的.产品级别的Spring应用. Spring Boot为Spring平台及第三方库提供开箱即用的设置,这样你就可 ...
随机推荐
- SQL Server 常用分页SQL(转)
发现网上好多都是错的.网上经常查到的那个Top Not in 或者Max 大部分都不实用,很多都忽略了Order和性能问题.为此上网查了查,顺带把2000和2012版本的也补上了. 先说说网上常见SQ ...
- python 中几个层次的中文编码.md
转自:[http://swj.me/] 介绍 一直不太喜欢使用命令行,所以去年年底的技术创新中,使用TkInter来开发小工具.结果花费了大量的时间来学习TkInter ui的使用. 最近想整理该工具 ...
- python基础-第六篇-6.2模块
python之强大,就是因为它其提供的模块全面,模块的知识点不仅多,而且零散---一个字!错综复杂 没办法,二八原则抓重点咯!只要抓住那些以后常用开发的方法就可以了,哪些是常用的?往下看--找答案~ ...
- MapReduce的核心编程思想
1.MapReduce的核心编程思想 2.yarn集群工作机制 3.maptask并行度与决定机制 4.maptask工作机制 5.MapReduce整体流程 6.shuffle机制 7.yarn架构
- js小数四舍五入,保留两位小数
直接用用number.toFixed(2)即可 <template> <section class="p-10"> <h1> {{ number ...
- Spark Standalone Mode 单机启动Spark -- 分布式计算系统spark学习(一)
spark是个啥? Spark是一个通用的并行计算框架,由UCBerkeley的AMP实验室开发. Spark和Hadoop有什么不同呢? Spark是基于map reduce算法实现的分布式计算,拥 ...
- JS生成随机字符串的多种方法
这篇文章主要介绍了JS生成随机字符串的方法,需要的朋友可以参考下 下面的一段代码,整理电脑时,记录备查. <script language="javascript"> ...
- python yield的终极解释
(译)Python关键字yield的解释(stackoverflow): http://stackoverflow.com/questions/231767/the-python-yield-keyw ...
- Spark SQL中UDF和UDAF
转载自:https://blog.csdn.net/u012297062/article/details/52227909 UDF: User Defined Function,用户自定义的函数,函数 ...
- Kafka笔记整理(一)
Kafka简介 消息队列(Message Queue) 消息 Message 网络中的两台计算机或者两个通讯设备之间传递的数据.例如说:文本.音乐.视频等内容. 队列 Queue 一种特殊的线性表(数 ...