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页码使用.

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

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

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

reasonable:启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页。比jpa中Pageable进行分页查询时更合理,不需要再去处理。

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

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.startPage(start,size,"id desc");

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

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

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

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

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快速入门(六)的更多相关文章

  1. 笔记61 Spring Boot快速入门(一)

    IDEA+Spring Boot快速搭建 一.IDEA创建项目 略 项目创建成功后在resources包下,属性文件application.properties中,把数据库连接属性加上,同时可以设置服 ...

  2. 笔记63 Spring Boot快速入门(三)

    SpringBoot中使用JSP Springboot的默认视图支持是Thymeleaf,但是Thymeleaf还没开始学,熟悉的还是jsp,所以要让Springboot支持 jsp. 一.在pom. ...

  3. 笔记65 Spring Boot快速入门(五)

    SpringBoot+JPA 一.什么是JPA? JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期 ...

  4. 笔记70 Spring Boot快速入门(八)(重要)

    上传文件 一.方式一 1.上传页面 upLoadPage.html <!DOCTYPE html> <html lang="en"> <head> ...

  5. 笔记64 Spring Boot快速入门(四)

    SpringBoot中错误处理.端口设置和上下文路径以及配置切换 一.错误处理 假设在访问首页的时候会出现一些错误,然后将这些错误当作异常抛出,反馈给用户. 1.修改IndexController.j ...

  6. 笔记62 Spring Boot快速入门(二)

    SpringBoot部署 一.jar方式 1.首先安装maven. <1>下载最新的maven版本:https://maven.apache.org/download.cgi <2& ...

  7. 笔记67 Spring Boot快速入门(七)

    SpringBoot+RESTful+JSON 一.RESTful架构 REST全称是Representational State Transfer,中文意思是表述(编者注:通常译为表征)性状态转移. ...

  8. Spring Boot 快速入门

    Spring Boot 快速入门 http://blog.csdn.net/xiaoyu411502/article/details/47864969 今天给大家介绍一下Spring Boot MVC ...

  9. Spring Boot快速入门(二):http请求

    原文地址:https://lierabbit.cn/articles/4 一.准备 postman:一个接口测试工具 创建一个新工程 选择web 不会的请看Spring Boot快速入门(一):Hel ...

随机推荐

  1. awk 起始位置和长度和 mf 一致

    1位开始 , 925开始 截取24 awk '{OFS="";print(substr($0,925,24),substr($0,1,24),substr($0,436,1),&q ...

  2. redis笔记3-命令

    通用命令:keys * --查询所有keykeys list* --查询list开头的keytype key1 --查询键对应的value类型del key --删除指定的keyttl key --查 ...

  3. python 常用技巧 — 数组 (array)

    目录: 1. 数组每一行除以这一行的总数(numpy divide row by row sum) 2. 数组每一行或者每一列求平均 (python average array columns or ...

  4. Spring 讲解(五)

    Spring 中使用 xml 配置开发和使用注解开发案例 1.Spring 中使用 xml 配置开发案例 接口 public interface UserDao { void add(User use ...

  5. Java中Calendar类的常用方法(对时间进行计算的类)

    例子: /**** * 传入具体日期 ,返回具体日期增加一个月. * @param date 日期(2017-04-13) * @return 2017-05-13 * @throws ParseEx ...

  6. 【leetcode】979. Distribute Coins in Binary Tree

    题目如下: Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and th ...

  7. 文本处理工具——sed进阶

    一sed的搜索替代 (一)常见的和替代相关的选项 搜索替代,和vim的写法很像 s///:查找替换,支持使用其它分隔符,s@@@,s### p: 显示替换成功的行,就是打印. w /PATH/TO/S ...

  8. mybatis generator工具集成(一)

    第一步,pom中加入 <build> <plugins> <plugin> <groupId>org.springframework.boot</ ...

  9. HTML5: HTML5 内联 SVG

    ylbtech-HTML5: HTML5 内联 SVG 1.返回顶部 1. HTML5 内联 SVG HTML5 支持内联 SVG. 什么是SVG? SVG 指可伸缩矢量图形 (Scalable Ve ...

  10. 5、java操作xml,dom4j

    . 1.首先在项目路径下引入dom4j-1.6.1.jar和jaxen-1.1-beta-6.jar包,jaxp方式解析xml文件 <?xml version="1.0" e ...