• 笔记66 Spring Boot快速入门(六)


    SpringBoot中使用Mybatis

    一、注解方式

    1.创建映射文件CategoryMapper.java

    使用注解@Mapper 表示这是一个Mybatis Mapper接口。
    使用@Select注解表示调用findAll方法会去执行对应的sql语句。

     1 package com.example.springbootmybatisdemo.mapper;
     2 
     3 import com.example.springbootmybatisdemo.pojo.Category;
     4 import org.apache.ibatis.annotations.Mapper;
     5 import org.apache.ibatis.annotations.Select;
     6 
     7 import java.util.List;
     8 
     9 
    10 @Mapper
    11 public interface CategoryMapper {
    12     @Select("select * from category")
    13     List<Category> findAll();
    14 }

    2.创建CategoryController.java

    有问题:无法自动加载mapper,显示有错误,但是运行结果正确。

     1 package com.example.springbootmybatisdemo.controller;
     2 
     3 import com.example.springbootmybatisdemo.mapper.CategoryMapper;
     4 import com.example.springbootmybatisdemo.pojo.Category;
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.ui.Model;
     8 import org.springframework.web.bind.annotation.RequestMapping;
     9 
    10 import java.util.List;
    11 
    12 @Controller
    13 public class CategoryController {
    14     @Autowired
    15     private CategoryMapper categoryMapper;
    16 
    17     @RequestMapping("/listCategory")
    18     public String listCategory(Model model) throws Exception{
    19         List<Category> categories=categoryMapper.findAll();
    20         model.addAttribute("category",categories);
    21         System.out.println();
    22         return "listCategory";
    23     }
    24 }

    3.listCategory.html

     1 <!DOCTYPE html>
     2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     5     <title>Title</title>
     6 </head>
     7 <body>
     8 <div class="showing">
     9     <h2>SpringBoot+mybatis</h2>
    10 
    11     <table>
    12         <thead>
    13         <tr>
    14             <th>id</th>
    15             <th>name</th>
    16         </tr>
    17         </thead>
    18         <tbody>
    19         <tr th:each="c: ${category}">
    20             <td align="center" th:text="${c.id}"></td>
    21             <td align="center" th:text="${c.name}"></td>
    22         </tr>
    23         </tbody>
    24     </table>
    25 </div>
    26 </body>
    27 </html>

    二、xml方式(有问题)

    三、SpringBoot+Mybatis抽插数据库

    1.使用第三方插件PageHelper进行分页查询

    增加依赖:

    1         <dependency>
    2             <groupId>com.github.pagehelper</groupId>
    3             <artifactId>pagehelper</artifactId>
    4             <version>4.1.6</version>
    5         </dependency>

    2.配置PageHelper

      PageHelperConfig.java

     1 package com.example.springbootmybatisdemo.config;
     2 
     3 import com.github.pagehelper.PageHelper;
     4 import org.springframework.context.annotation.Bean;
     5 import org.springframework.context.annotation.Configuration;
     6 
     7 import java.util.Properties;
     8 
     9 @Configuration
    10 public class PageHelperConfig {
    11     @Bean
    12     public PageHelper pageHelper(){
    13         PageHelper pageHelper = new PageHelper();
    14         Properties p = new Properties();
    15         p.setProperty("offsetAsPageNum", "true");
    16         p.setProperty("rowBoundsWithCount", "true");
    17         p.setProperty("reasonable", "true");
    18         pageHelper.setProperties(p);
    19         return pageHelper;
    20     }
    21 }

    注解@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

     1 package com.example.springbootmybatisdemo.mapper;
     2 
     3 import com.example.springbootmybatisdemo.pojo.Category;
     4 import org.apache.ibatis.annotations.*;
     5 
     6 import java.util.List;
     7 
     8 
     9 @Mapper
    10 public interface CategoryMapper {
    11     @Select("select * from category")
    12     List<Category> findAll();
    13 
    14     @Insert("insert into category(name) values (#{name})")
    15     int save(Category category);
    16 
    17     @Delete(" delete from category where id= #{id} ")
    18      void delete(int id);
    19 
    20     @Select("select * from category where id= #{id} ")
    21     Category get(int id);
    22 
    23     @Update("update category set name=#{name} where id=#{id} ")
    24     int update(Category category);
    25 }

    4.控制层

    CategoryController.java

     1 package com.example.springbootmybatisdemo.controller;
     2 
     3 import com.example.springbootmybatisdemo.mapper.CategoryMapper;
     4 import com.example.springbootmybatisdemo.pojo.Category;
     5 import com.github.pagehelper.PageHelper;
     6 import com.github.pagehelper.PageInfo;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Controller;
     9 import org.springframework.ui.Model;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.RequestParam;
    12 
    13 import java.util.List;
    14 
    15 @Controller
    16 public class CategoryController {
    17     @Autowired
    18     private CategoryMapper categoryMapper;
    19 
    20     @RequestMapping("/listCategory")
    21     public String listCategory(Model model) throws Exception{
    22         List<Category> categories=categoryMapper.findAll();
    23         model.addAttribute("category",categories);
    24         System.out.println();
    25         return "listCategory";
    26     }
    27 
    28     @RequestMapping("/listCategories")
    29     public String listCategories(Model model,
    30                                  @RequestParam(value = "start",defaultValue = "0")int start,
    31                                  @RequestParam(value = "size",defaultValue = "5") int size) throws Exception{
    32         PageHelper.startPage(start,size,"id desc");
    33         List<Category> categories=categoryMapper.findAll();
    34         PageInfo<Category> pageInfo=new PageInfo<>(categories);
    35         System.out.println(pageInfo.getPageNum());
    36         model.addAttribute("pageInfo",pageInfo);
    37         return "listCategories";
    38     }
    39 
    40     @RequestMapping("/addCategory")
    41     public String addCategory(Category category) throws Exception{
    42         categoryMapper.save(category);
    43         return "redirect:listCategories";
    44     }
    45     @RequestMapping("/deleteCategory")
    46     public String deleteCategory(Category category)throws Exception{
    47         categoryMapper.delete(category.getId());
    48         return "redirect:listCategories";
    49     }
    50     @RequestMapping("/updateCategory")
    51     public String updateCategory(Category category)throws Exception{
    52         categoryMapper.update(category);
    53         return "redirect:listCategories";
    54     }
    55     @RequestMapping("/editCategory")
    56     public String editCategory(int id,Model model)throws Exception{
    57         Category category=categoryMapper.get(id);
    58         model.addAttribute("category",category);
    59         return "editCategory";
    60     }
    61 
    62 
    63

    根据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

     1 <!DOCTYPE html>
     2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     5     <title>Title</title>
     6 </head>
     7 <body>
     8 <div class="showing">
     9     <h2>SpringBoot+Mybatis</h2>
    10     <div style="500px;margin:20px auto;text-align: center">
    11         <table align="center" border="1" cellspacing="0">
    12             <thead>
    13             <tr>
    14                 <th>id</th>
    15                 <th>name</th>
    16                 <td>编辑</td>
    17                 <td>删除</td>
    18             </tr>
    19             </thead>
    20             <tbody>
    21             <tr th:each="c: ${pageInfo.list}">
    22                 <td align="center" th:text="${c.id}"></td>
    23                 <td align="center" th:text="${c.name}"></td>
    24                 <td align="center" ><a th:href="@{/editCategory(id=${c.id})}">编辑</a></td>
    25                 <td align="center" ><a th:href="@{/deleteCategory(id=${c.id})}">删除</a></td>
    26             </tr>
    27             </tbody>
    28         </table>
    29         <br />
    30         <div>
    31             <a th:href="@{/listCategories(start=1)}">[首  页]</a>
    32             <a th:href="@{/listCategories(start=${pageInfo.pageNum -1})}">[上一页]</a>
    33             <a th:href="@{/listCategories(start=${pageInfo.pageNum +1})}">[下一页]</a>
    34             <a th:href="@{/listCategories(start=${pageInfo.pages})}">[末  页]</a>
    35         </div>
    36         <form action="/addCategory" method="post">
    37             name:<input name="name"/><br/>
    38             <button type="submit">提交</button>
    39         </form>
    40     </div>
    41 </div>
    42 </body>
    43 </html>

    editCategory.html

     1 <!DOCTYPE html>
     2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
     3 <head>
     4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     5     <title>Title</title>
     6 </head>
     7 <body>
     8 <div class="showing">
     9     <h2>springboot+jpa</h2>
    10 
    11     <div style="margin:0px auto; 500px">
    12 
    13         <form action="/updateCategory" method="post">
    14 
    15             name: <input name="name" th:value="${category.name}" /> <br/>
    16 
    17             <input name="id" type="hidden" th:value="${category.id}" />
    18             <button type="submit">提交</button>
    19 
    20         </form>
    21     </div>
    22 </div>
    23 </body>
    24 </html>

    5.测试

    6.问题:当编辑完以后就返回首页了。

    修改:在编辑时传入当前分页数,然后跳转到listCategories的时候传入start。

    四、代码

    https://github.com/lyj8330328/springboot-mybatis-demo

  • 相关阅读:
    CAAnimation动画相关文章
    [源代码]List的增加与删除
    [原创]c# 类中 Collection 字段初始化的特殊之处
    c# 多数值区间判断是否有重叠
    将M个客服随机分配给N个客户
    c# IList.ToList()后更改元素值会不会影响原列表的值
    java单元测试之Mock静态方法
    java的Spring学习2- junit和mock
    java mybatis学习二
    java8 方法引用与lambda
  • 原文地址:https://www.cnblogs.com/lyj-gyq/p/9306735.html
Copyright © 2020-2023  润新知