笔记66 Spring Boot快速入门(六)
SpringBoot中使用Mybatis
一、注解方式
1.创建映射文件CategoryMapper.java
使用注解@Mapper 表示这是一个Mybatis Mapper接口。
使用@Select注解表示调用findAll方法会去执行对应的sql语句。
package com.example.springbootmybatisdemo.mapper; import com.example.springbootmybatisdemo.pojo.Category;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper
public interface CategoryMapper {
@Select("select * from category")
List<Category> findAll();
}
2.创建CategoryController.java
有问题:无法自动加载mapper,显示有错误,但是运行结果正确。

package com.example.springbootmybatisdemo.controller; import com.example.springbootmybatisdemo.mapper.CategoryMapper;
import com.example.springbootmybatisdemo.pojo.Category;
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 java.util.List; @Controller
public class CategoryController {
@Autowired
private CategoryMapper categoryMapper; @RequestMapping("/listCategory")
public String listCategory(Model model) throws Exception{
List<Category> categories=categoryMapper.findAll();
model.addAttribute("category",categories);
System.out.println();
return "listCategory";
}
}
3.listCategory.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>SpringBoot+mybatis</h2> <table>
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr th:each="c: ${category}">
<td align="center" th:text="${c.id}"></td>
<td align="center" th:text="${c.name}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
二、xml方式(有问题)
三、SpringBoot+Mybatis抽插数据库
1.使用第三方插件PageHelper进行分页查询
增加依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
2.配置PageHelper
PageHelperConfig.java
package com.example.springbootmybatisdemo.config; import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.Properties; @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;
}
}
注解@Configuration 表示PageHelperConfig 这个类是用来做配置的。
注解@Bean 表示启动PageHelper这个拦截器。
offsetAsPageNum:设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用.
rowBoundsWithCount:设置为true时,使用RowBounds分页会进行count查询.
reasonable:启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页。比jpa中Pageable进行分页查询时更合理,不需要再去处理。
3.修改映射mapper
CategoryMapper.java
package com.example.springbootmybatisdemo.mapper; import com.example.springbootmybatisdemo.pojo.Category;
import org.apache.ibatis.annotations.*; import java.util.List; @Mapper
public interface CategoryMapper {
@Select("select * from category")
List<Category> findAll(); @Insert("insert into category(name) values (#{name})")
int save(Category category); @Delete(" delete from category where id= #{id} ")
void delete(int id); @Select("select * from category where id= #{id} ")
Category get(int id); @Update("update category set name=#{name} where id=#{id} ")
int update(Category category);
}
4.控制层
CategoryController.java
package com.example.springbootmybatisdemo.controller; import com.example.springbootmybatisdemo.mapper.CategoryMapper;
import com.example.springbootmybatisdemo.pojo.Category;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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 java.util.List; @Controller
public class CategoryController {
@Autowired
private CategoryMapper categoryMapper; @RequestMapping("/listCategory")
public String listCategory(Model model) throws Exception{
List<Category> categories=categoryMapper.findAll();
model.addAttribute("category",categories);
System.out.println();
return "listCategory";
} @RequestMapping("/listCategories")
public String listCategories(Model model,
@RequestParam(value = "start",defaultValue = "0")int start,
@RequestParam(value = "size",defaultValue = "5") int size) throws Exception{
PageHelper.startPage(start,size,"id desc");
List<Category> categories=categoryMapper.findAll();
PageInfo<Category> pageInfo=new PageInfo<>(categories);
System.out.println(pageInfo.getPageNum());
model.addAttribute("pageInfo",pageInfo);
return "listCategories";
} @RequestMapping("/addCategory")
public String addCategory(Category category) throws Exception{
categoryMapper.save(category);
return "redirect:listCategories";
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category category)throws Exception{
categoryMapper.delete(category.getId());
return "redirect:listCategories";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category category)throws Exception{
categoryMapper.update(category);
return "redirect:listCategories";
}
@RequestMapping("/editCategory")
public String editCategory(int id,Model model)throws Exception{
Category category=categoryMapper.get(id);
model.addAttribute("category",category);
return "editCategory";
} }
根据start,size进行分页,并且设置id 倒排序
因为PageHelper的作用,这里就会返回当前分页的集合了
根据返回的集合,创建PageInfo对象
5.视图层
listCategories.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>SpringBoot+Mybatis</h2>
<div style="width:500px;margin:20px auto;text-align: center">
<table align="center" border="1" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>name</th>
<td>编辑</td>
<td>删除</td>
</tr>
</thead>
<tbody>
<tr th:each="c: ${pageInfo.list}">
<td align="center" th:text="${c.id}"></td>
<td align="center" th:text="${c.name}"></td>
<td align="center" ><a th:href="@{/editCategory(id=${c.id})}">编辑</a></td>
<td align="center" ><a th:href="@{/deleteCategory(id=${c.id})}">删除</a></td>
</tr>
</tbody>
</table>
<br />
<div>
<a th:href="@{/listCategories(start=1)}">[首 页]</a>
<a th:href="@{/listCategories(start=${pageInfo.pageNum -1})}">[上一页]</a>
<a th:href="@{/listCategories(start=${pageInfo.pageNum +1})}">[下一页]</a>
<a th:href="@{/listCategories(start=${pageInfo.pages})}">[末 页]</a>
</div>
<form action="/addCategory" method="post">
name:<input name="name"/><br/>
<button type="submit">提交</button>
</form>
</div>
</div>
</body>
</html>
editCategory.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title</title>
</head>
<body>
<div class="showing">
<h2>springboot+jpa</h2> <div style="margin:0px auto; width:500px"> <form action="/updateCategory" method="post"> name: <input name="name" th:value="${category.name}" /> <br/> <input name="id" type="hidden" th:value="${category.id}" />
<button type="submit">提交</button> </form>
</div>
</div>
</body>
</html>
5.测试

6.问题:当编辑完以后就返回首页了。
修改:在编辑时传入当前分页数,然后跳转到listCategories的时候传入start。
四、代码
https://github.com/lyj8330328/springboot-mybatis-demo
笔记66 Spring Boot快速入门(六)的更多相关文章
- 笔记61 Spring Boot快速入门(一)
IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...
- 笔记63 Spring Boot快速入门(三)
SpringBoot中使用JSP Springboot的默认视图支持是Thymeleaf,但是Thymeleaf还没开始学,熟悉的还是jsp,所以要让Springboot支持 jsp. 一.在pom. ...
- 笔记65 Spring Boot快速入门(五)
SpringBoot+JPA 一.什么是JPA? JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期 ...
- 笔记70 Spring Boot快速入门(八)(重要)
上传文件 一.方式一 1.上传页面 upLoadPage.html <!DOCTYPE html> <html lang="en"> <head> ...
- 笔记64 Spring Boot快速入门(四)
SpringBoot中错误处理.端口设置和上下文路径以及配置切换 一.错误处理 假设在访问首页的时候会出现一些错误,然后将这些错误当作异常抛出,反馈给用户. 1.修改IndexController.j ...
- 笔记62 Spring Boot快速入门(二)
SpringBoot部署 一.jar方式 1.首先安装maven. <1>下载最新的maven版本:https://maven.apache.org/download.cgi <2& ...
- 笔记67 Spring Boot快速入门(七)
SpringBoot+RESTful+JSON 一.RESTful架构 REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. ...
- Spring Boot 快速入门
Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...
- Spring Boot快速入门(二):http请求
原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...
随机推荐
- shell使用reposync同步仓库
- [javascript模块化]require.js简单使用
1.javascript模块规范 CommonJS 主要用于服务器端编程,比如node.js的模块系统,就是参照CommonJS规范实现的.在CommonJS中,有一个全局性方法require(),用 ...
- [javase基础] JDK JRE JVM的区别?
JDK Java Development Kit 用作开发, 包含了JRE,编译器和其他的工具(比如: JavaDoc,Java调试器),可以让开发者开发.编译.执行Java应用程序. JRE Jav ...
- python2和python3中TestSuite().addTest的区别
Python2中unittest.TestSuite().addTest()的参数是这样的:unittest.TestSuite().addTest(TestFun("test_nam&qu ...
- Android中软键盘弹出时关于布局的问题
当在Android的layout设计里面如果输入框过多,则在输入弹出软键盘的时候,下面的输入框会有一部分被软件盘挡住,从而不能获取焦点输入. 解决办法: 方法一:在你的activity中的oncre ...
- BZOJ 3569: DZY Loves Chinese II(线性基)
传送门 解题思路 首先构造出一个生成树,考虑不连接的情况.假设连通两点的非树边和树边都断掉后不连通,那么可以给所有的非树边随机一个互不相同的值,然后树边的权值为过他两端点的非树边权值的异或和,这个可以 ...
- python基础三(深浅拷贝)
1.赋值操作 list_1 = [1,2,3,['barry','Jerry']] list_2 = list_1 list_1[0] = 111 print(list_1) # [111, 2, 3 ...
- 尚学linux课程---12、vim操作命令2
尚学linux课程---12.vim操作命令2 一.总结 一句话总结: 要看不同的视频,每个视频的关键点都不一样,不如之间的的视频就没讲到vim中set nu是什么意思 学了的内容一定要练,不然真的是 ...
- HDU 1875 畅通工程再续 (Prim)
题目链接:HDU 1875 Problem Description 相信大家都听说一个"百岛湖"的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现 ...
- LeetCode N皇后 & N皇后 II
题目链接:https://leetcode-cn.com/problems/n-queens/ 题目链接:https://leetcode-cn.com/problems/n-queens-ii/ 题 ...