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平台及第三方库提供开箱即用的设置,这样你就可 ...
随机推荐
- ORACLE内存结构:PGA And UGA,ORACLE用户进程、服务器进程
执行一个SQL语句 执行查询语句的过程: 用户进程执行一个查询语句如select * from emp where empno=7839 用户进程和服务器进程建立连接,把改用户进程的信息存储到PGA的 ...
- 627. Swap Salary
627. Swap Salary SQL Schema Given a table salary, such as the one below, that has m=male and f=femal ...
- 【python】常用函数
使用list生成dict(可指定单条长度和数据类型,splen为4即为list中每4行组成dict中一条) def list2dict(srclist,splen,datatype):# dataty ...
- nsq小试牛刀-0.3.0 API变更
NSQ是由知名短链接服务商bitly用Go语言开发的实时消息处理系统,具有高性能.高可靠.无视单点故障等优点,是一个非常不错的新兴的消息队列解决方案. nsg易于配置和部署,所有参考都通过命令行指定, ...
- Android开发:带动画的分享效果
这几天做了个带动画的分享页面.如今把它分享出来,假设你认为实用,请直接使用,避免反复造轮子 先看下效果图 认为仅仅是看效果图不明显.那么用手机扫描以下的二维码下载安装包:
- robotium原理之获取WebElement元素
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/hunterno4/article/details/35569665 robotium ...
- MYSQL中,CAST函数的使用规则
CAST函数语法规则是:Cast(字段名 as 转换的类型 ),其中类型可以为: CHAR[(N)] 字符型 DATE 日期型DATETIME 日期和时间型DECIMAL float型SIGNED i ...
- Spark2.0机器学习系列之8:多类分类问题(方法归总和分类结果评估)
一对多(One-vs-Rest classifier) 将只能用于二分问题的分类(如Logistic回归.SVM)方法扩展到多类. 参考:http://www.cnblogs.com/CheeseZH ...
- win下如何解决在chrome的同源访问问题
引子:本来是想验证如果在网页中包含多个框架,那么就会存在两个以上的不同全局环境,如果从一个框架引用另一个框架的数据比如数组a,那么用 instanceof 判断这个数组a是不是另个框架Array的实例 ...
- Linux系统常用命令汇总
命令格式:命令 -选项 参数,例如:ls -la /usr:当有多个选项时,可以写在一起.ifconfig:查看当前机器的IP信息service network restart:重启网络服务servi ...