MyBatis和elementui中的高级查询和分页

前台

我们需要发送请求和带入参数

有了这两个属性过后需要在data中添加

这个属性是和方法平级的

整个页面

<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.keywords" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getEmployees">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="id" width="60" label="ID">
            </el-table-column>
            <el-table-column prop="username" label="姓名" width="120" sortable>
            </el-table-column>
            <el-table-column prop="sn" label="员工编号" width="80" sortable>
            </el-table-column>
            <el-table-column prop="password" label="密码" width="280" sortable>
            </el-table-column>
            <el-table-column prop="headimg" label="头像" width="180" sortable>
            </el-table-column>
            <el-table-column prop="phone" label="电话" width="180" sortable>
            </el-table-column>
            <el-table-column prop="department" label="部门" width="180" sortable>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条
        page-size为每页显示的条数-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="editForm.username" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="姓名" prop="username">
                    <el-input v-model="addForm.username" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from ‘../../common/js/util‘
    //import NProgress from ‘nprogress‘
    import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from ‘../../api/api‘;

    export default {
        data() {
            return {
                filters: {
                    keywords: ‘‘,

                },
                employees: [],
                total: 0,
                page: 1,
                pageSize:5,
                listLoading: false,
                sels: [],//列表选中列

                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        { required: true, message: ‘请输入姓名‘, trigger: ‘blur‘ }
                    ]
                },
                //编辑界面数据
                editForm: {
                    username: ‘‘,
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [
                        { required: true, message: ‘请输入姓名‘, trigger: ‘blur‘ }
                    ]
                },
                //新增界面数据
                addForm: {
                    username: ‘‘,
                }

            }
        },
        methods: {
            //性别显示转换
            formatSex: function (row, column) {
                return row.sex == 1 ? ‘男‘ : row.sex == 0 ? ‘女‘ : ‘未知‘;
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getEmployees();
            },
            //获取用户列表
            getEmployees() {
                let para = {
                    page: this.page,
                    pageSize:this.pageSize,
                    keywords: this.filters.keywords
                };
                this.listLoading = true;
                //NProgress.start();
                //getUserListPage(para)
                this.$http.patch("/employee/query",para).then((res) => {
                    this.total=res.data.total;
                    this.employees = res.data.rows;
                    this.listLoading=false;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm(‘确认删除该记录吗?‘, ‘提示‘, {
                    type: ‘warning‘
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { id: row.id };
                    //console.log(row.id);
                    this.$http.delete(‘/employee/delete/‘+para.id).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: ‘删除成功‘,
                            type: ‘success‘
                        });
                        this.getEmployees();
                    });
                }).catch(() => {
                    this.$message({
                        message: ‘删除失败‘,
                        type: ‘error‘
                    });
                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    username:‘‘
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm(‘确认提交吗?‘, ‘提示‘, {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            // para.birth = (!para.birth || para.birth == ‘‘) ? ‘‘ : util.formatDate.format(new Date(para.birth), ‘yyyy-MM-dd‘);
                            this.$http.put("/employee/update",para).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: ‘提交成功‘,
                                    type: ‘success‘
                                });
                                this.$refs[‘editForm‘].resetFields();
                                this.editFormVisible = false;
                                this.getEmployees();
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm(‘确认提交吗?‘, ‘提示‘, {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            console.log(para);
                            // para.birth = (!para.birth || para.birth == ‘‘) ? ‘‘ : util.formatDate.format(new Date(para.birth), ‘yyyy-MM-dd‘);
                            this.$http.post("/employee/add",para).then((res) => {
                                this.addLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: ‘提交成功‘,
                                    type: ‘success‘
                                });
                                this.$refs[‘addForm‘].resetFields();
                                this.addFormVisible = false;
                                this.getEmployees();
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm(‘确认删除选中记录吗?‘, ‘提示‘, {
                    type: ‘warning‘
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    batchRemoveUser(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: ‘删除成功‘,
                            type: ‘success‘
                        });
                        this.getEmployees();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getEmployees();
        }
    }
    function pagination(index,size,list){
        return list.slice((index-1)*size,index*size);
    }
</script>

<style scoped>

</style>

后台web

首先需要一个返回值

PageList

package cn.jiedada;

import java.util.List;

public class PageList<T> {
    private Long total;
    private List<T> rows;

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public PageList(Long total, List<T> rows) {
        this.total = total;
        this.rows = rows;
    }

    public PageList() {
    }
}

和一个接收参数的类

EmployeeQuery

public class EmployeeQuery extends BasicQuery {
}

BasicQuery

package cn.jiedada.query;

public class BasicQuery {
    private Long page;
    //默认为每页10张数据
    private Long pageSize=10L;
    //高级查询的关键字
    private String keywords;

    public String getKeywords() {
        return keywords;
    }

    public void setKeywords(String keywords) {
        this.keywords = keywords;
    }

    public Long getPageSize() {
        return pageSize;
    }

    public void setPageSize(Long pageSize) {
        this.pageSize = pageSize;
    }

    public Long getPage() {
        return page;
    }

    public void setPage(Long page) {
        this.page = page;
    }
    //设置每页开始的页数,limit start,通过get可以直接获得#{start}
    public Long getStart(){
        return (this.page-1)*pageSize;
    }
}

web

@RequestMapping(value = "/query",method = RequestMethod.PATCH)
    @ResponseBody
    //@RequestBody才能把前台的json转为后台的数据
    public PageList<Employee> query(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.query(employeeQuery);
    }

后台service

因为每个页面都需要使用分页和高级查询所以我们在父类中写入

IBasicService

package cn.jiedada.service;

import cn.jiedada.PageList;
import cn.jiedada.query.BasicQuery;

import java.io.Serializable;
import java.util.List;

public interface IBasicService<T> {
    void save(T t);
    void delete(Serializable id);
    void update(T t);
    List<T> findAll();
    T findOne(Serializable id);

    PageList<T> query(BasicQuery basicQuery);
}

BasicServiceImpl

package cn.jiedada.service.impl;

import cn.jiedada.PageList;
import cn.jiedada.mapper.BasicMapper;
import cn.jiedada.query.BasicQuery;
import cn.jiedada.service.IBasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class BasicServiceImpl<T> implements IBasicService<T> {
    @Autowired
    private BasicMapper<T> basicMapper;
    @Override
    @Transactional
    public void save(T t) {
        basicMapper.save(t);
    }

    @Override
    @Transactional
    public void delete(Serializable id) {
        basicMapper.delete(id);
    }

    @Override
    @Transactional
    public void update(T t) {
        basicMapper.update(t);
    }

    @Override
    public List<T> findAll() {
        return basicMapper.findAll();
    }

    @Override
    public T findOne(Serializable id) {
        return basicMapper.findOne(id);
    }

    @Override
    public PageList<T> query(BasicQuery basicQuery) {
        //  通过Mapper查询总数
        Long total = basicMapper.querryCount(basicQuery);
        //查询当前页数据
        List<T> rows = basicMapper.queryData(basicQuery);
        //通过构造方法返回数据中的所有值
        return new PageList<T>(total,rows);
    }
}

后台mapper

BasicMapper

package cn.jiedada.mapper;

import cn.jiedada.query.BasicQuery;

import java.io.Serializable;
import java.util.List;

public interface BasicMapper<T> {
    void save(T t);
    void delete(Serializable id);
    void update(T t);
    List<T> findAll();
    T findOne(Serializable id);
    //查询总页数
    Long querryCount(BasicQuery basicQuery);
    //查询分页1的所有数据
    List<T> queryData(BasicQuery basicQuery);
}

后台mapper.xml

通过继承和实现EmployeeMapper和EmployeeService也有我们的东西了,只需要实现Mapper中的方法我们就可以完成了

在其中添加

<!--查询总页数
    记住需要添加where条件
    -->
    <select id="querryCount" parameterType="employeeQuery" resultType="long">
        select count(id) from t_employee
        <where>
            <include refid="sqlWhere"></include>
        </where>
    </select>
    <!--查询pageList-->
    <select id="queryData" parameterType="employeeQuery" resultType="employee">
        select * from t_employee
        <where>
            <include refid="sqlWhere"></include>
        </where>
        LIMIT #{start},#{pageSize}
    </select>
    <!--高级查询,判断是否传入来了keywords-->
    <sql id="sqlWhere">
        <if test="keywords!=null and keywords!=‘‘">
            and username like concat(‘%‘,#{keywords},‘%‘)
        </if>
    </sql>

原文地址:https://www.cnblogs.com/xiaoruirui/p/11832652.html

时间: 2024-07-30 07:09:22

MyBatis和elementui中的高级查询和分页的相关文章

mysql中的高级查询

mysql中的高级查询 以前学习的查询语法:   select 字段名 from 表名 where 条件   其实,查询的语法变化很多: 1. select 可以查询表达式, 表达式就是 运算符+操作数. 比如 1 + 1   2 * 3  2-1+5*9   Math.random() * 1; 可以看出,数据库中,字符串+字符串不是拼接,而是计算加法, 试一试,拿着'1' + 'a123'. 扩充,如果非要让两个字符串是拼接,咋办? 2. 表的别名     其实列也可以起别名:   3. d

LINQ中的高级查询

LINQ查询方法: 1.Method Syntax查询方法方式:主要利用System.Linq.Enumerable类定义的拓展方法和Lambda表达式方法进行查询. 2.Query Syntax查询语句方式. 查询语句和查询方法的关系:编译器负责在编译时将查询语句便以为查询方法,大部分的查询方法都有对应的查询语句姓氏.一般情况下,我们会使用查询语句+查询方法的混合方式进行查询. 常见的高级查询方法分为:聚合.排序.分区.集合.生成. Ⅰ聚合类: <span style="font-siz

Linq高级查询与分页查询

Linq高级查询 以~开头: r=>r.Name.StartsWith("李"); 以~结尾: r=>r.Name.EndsWith("光"); 包含(模糊查询): r=>r.Name.Contains("四"); 数据总个数: Con.Goods.Count();||Con.Users.ToList().count; 最大值: Con.Goods.ToList().Max(r=>r.Price); 最小值: Con.Go

高级查询及分页总结

一.子查询 案例:  select * from Student where Birthday>( select Birthday from Student Where StudentName='张玲' ) 提示:将子查询和比较运算符联合使用,必须保证子查询返回的值不能多于一个. 二.IN和NOT IN子查询 1.IN 用IN条件:在不确保返回值的是一条的情况用IN. select studentname,studentnofrom studentwhere studentno in( sele

mongo中的高级查询之聚合操作(distinct,count,group)

1.distinct的实现: db.consumerecords.distinct("userId"):键值去重  类似于mysql中的 select distinct userId from consumerecords db.consumerecords.distinct("userId",{act:"charge"}):过滤之后去重,类似于mysql中的select distinct userId from consumerecords w

mybatis之xml中日期时间段查询的sql语句

<if test="startDate!=null and startDate!=''"> and CREATEDATE >=#{startDate}</if> <if test="endDate!=null and endDate!=''"> and CREATEDATE <=#{endDate}</if> 三个日期字段存入数据库都是字符串,不是date型,xml中>,<不能被正确解析,需要X

高级查询与分页

一.简单子查询 问题1:查询学生表中比美羊羊小的学员信息(姓名,地址) (不用变量,所想即所得) 1 select StudentName,Address from Student 2 where Birthday>(select Birthday from Student where StudentName=‘美羊羊’) 问题2:查询oop课程至少一次考试刚好等于60分的学生信息(姓名,成绩) 1 select StudentName,StudentResult 2 from Student,

2017-6-2 Linq 高级查询 (分页和组合查)、集合取交集

1.linq分页和组合查询:(用项目实战来解释) <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <he

Linq高级查询,分页查询及查询分页结合

1.以...开头    StartsWith Repeater1.DataSource=con.Users.Where(r=>r.Nickname.StartsWith("李")); Repeater1.DataBind(); 2.以...结尾     EndsWith Repeater1.DataSource=con.Users.Where(r=>r.Nickname.EndsWith("同")); Repeater1.DataBind(); 3.模糊