实现分页查询+批量删除

实体类(entity)

复制代码
package com.example.mybatis2.entity;

import java.io.Serializable;
//Serializable实现序列化
public class Category implements Serializable {
    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;
    }

    @Override
    public String toString() {
        return "Category{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
View Code
复制代码

业务类(dao)

复制代码
package com.example.mybatis2.dao;

import com.example.mybatis2.entity.Category;

import java.util.List;

public interface CategoryDao {
    //实现分页
    List<Category> findAll(int a);
    //批量删除
    public int deleteById(List<Integer> a);
}
View Code
复制代码

自动创建的Application

复制代码
package com.example.mybatis2;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mybatis2.dao")
public class MyBatis2Application {

    public static void main(String[] args) {
        SpringApplication.run(MyBatis2Application.class, args);
    }

}
View Code
复制代码

控制器(contorller)

复制代码
package com.example.mybatis2.controller;

import com.example.mybatis2.dao.CategoryDao;
import com.example.mybatis2.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.annotation.WebServlet;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RestController
//实现跨域
//@CrossOrigin(origins = "*",maxAge = 3600)
public class HelloController {
    @Autowired
    CategoryDao categoryDao;

    @GetMapping("hello")
    public List<Category> findAll(@RequestParam int a){
        int i=0;
        if(a==1){
            i=0;
        }
        else if(a==0){
            i=0;
        }
        else{
             i = (a-1) * 10;
        }
        return categoryDao.findAll(i);
    }

    @DeleteMapping("/deleteById")
    @ResponseBody
    public int deleteBYId(@RequestParam(value = "id") List<Integer> item){
        int a=categoryDao.deleteById(item);
        return  a;
    }
}
View Code
复制代码

页面代码(index.html)

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>

  <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

  <!-- 可选的 Bootstrap 主题文件(一般不用引入) -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
        integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
          integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
          crossorigin="anonymous"></script>

  <script src="./js/axios.min.js"></script>
  <script src="./js/jquery-3.5.1.min.js"></script>
  <script src="./js/vue.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.js"></script>
</head>
<body>

<div id="app">
  <h1>分页查询</h1>
  <button @click="deleteAll()">批量删除</button>
  <table width="100%" border="1">
    <tr v-for="(book,index) in books">
      <td style="text-align: center;"><input type="checkbox" name="bookId" :value="book.id"></td>
      <td>{{book.id}}</td>
      <td>{{book.name}}</td>
      <td style="text-align: center">
        <button onclick="up(this)" v-if="book.state=='已完成'">未完成</button>
        <button onclick="up(this)" v-if="book.state=='未完成'">已完成</button>
        <button @click="del(index)">删除</button>
      </td>
    </tr>
  </table>

  <nav aria-label="Page navigation">
    <ul class="pagination">
      <li>
        <a href="#" aria-label="Previous">
          <span aria-hidden="true">&laquo;</span>
        </a>
      </li>
      <li><a href="#" @click="add($event)">1</a></li>
      <li><a href="#" @click="add($event)">2</a></li>
      <li><a href="#" @click="add($event)">3</a></li>
      <li>
        <a href="#" aria-label="Next">
          <span aria-hidden="true">&raquo;</span>
        </a>
      </li>
    </ul>
  </nav>
</div>
<script>
  var app = new Vue({
    el: "#app",
    data: {
      books: []
    },
    created() {
      axios.get('/hello', {
        params: {
          a: 0
        }
      }).then(function (response) {
        app.books = response.data;
      })
              .catch(function (error) {
                console.log(error);
              })
              .then(function () {
              });
    },
    methods: {
      add: function (event) {
        let a = (event.currentTarget.innerHTML);
        axios.get('http://localhost:8080/hello', {
          params: {
            a: a
          }
        }).then(function (response) {
          app.books = response.data;
        })
                .catch(function (error) {
                  console.log(error);
                })
                .then(function () {
                });
      },
      del: function (id) {

        axios.get('/selectAll/del', {
          params: {
            id: id
          }
        }).then(function (response) {
          app.books = response.data;
        })
                .catch(function (error) {
                  console.log(error);
                })
                .then(function () {
                });
      },
      deleteAll: function () {
        let qs = Qs;
        // 得复选框已选中的值
        var items = $('input[name="bookId"]');
        var userIds = new Array();
        for (var x in items) {
          if (items[x].checked) userIds.push(items[x].value);
        }
        console.log(userIds);
        axios.request({
          url: `/deleteById`,
          method: 'delete',
          params:{
            id:userIds
          },
          // 重点在这里
          paramsSerializer: params => {
            return qs.stringify(params, { indices: false })
          }
        }).then(function (response) {
            let a=response.data;
            if(a>0){
              location.reload();
            }
        })
                .catch(function (error) {
                  console.log(error);
                })
                .then(function () {
                });;
      }

    }
  });
</script>

</body>
</html>
View Code
复制代码

创建application.yaml文件实现连接数据库

复制代码
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/gomall?serverTimezone=GMT&useUnicode=true&characterEncoding=utf-8
    username: root #用户名
    password: "000821" #密码

mybatis:
  type-aliases-package: com.example.mybatis2.entity
  mapper-locations: classpath:/mapper/*.xml
View Code
复制代码

创建mapper包,在这个包下面创建CategoryDao.xml,可以自定义命名

演示:

 

 

复制代码
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
-->
<mapper namespace="com.example.mybatis2.dao.CategoryDao">
    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为findAll,id属性值必须是唯一的,不能够重复,且与接口中的一致
,resultType属性指明查询返回的结果集类型,因为设置了别名,这里直接用类名即可
-->
    <select id="findAll" resultType="Category">
        select id,name from category LIMIT #{a},10;
    </select>
    
    
    <delete id="deleteById">
        delete from category where id in
        <foreach collection="list" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>
</mapper>
View Code
复制代码

数据库gomall(sql语句),剩下的数据自己添加多条

复制代码
create table category
(
  int id primary key not null,
    
 name char(20) not null,              
)

insert into category(id,name) values
(1,"rew"),
(2,"wqeq")...
View Code
复制代码

 

posted @   凡若沉曦'  阅读(119)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
js脚本
点击右上角即可分享
微信分享提示