赞
踩
MyBatis-Plus 使用简单,内置通用 Mapper、通用 Service,仅仅通过少量配置,即可实现单表大部分 CRUD 操作。下面介绍使用 service 中的 page 方法结合 Layui 前端框架,较快速的实现分页效果。
1.导入MyBatis-Plus依赖
- <!--mybatis-plus的springboot支持-->
- <dependency>
- <groupId>com.baomidou</groupId>
- <artifactId>mybatis-plus-boot-starter</artifactId>
- <version>3.1.1</version>
- </dependency>
2.编写接口--UserMapper
- package com.jk.mapper;
-
- import com.baomidou.mybatisplus.core.mapper.BaseMapper;
- import com.jk.entity.Userinfo;
-
- public interface UserMapper extends BaseMapper<Userinfo> {
- }
3.编写 service 接口--UserService ,并继承 IService。
- package com.jk.service;
-
- import com.baomidou.mybatisplus.extension.service.IService;
- import com.jk.entity.Userinfo;
-
- public interface UserService extends IService<Userinfo> {
- }
4.编写 service 实现类--UserServiceImpl,继承 MyBatis-Plus 的 ServiceImpl ,同时实现 UserService 接口。
- package com.jk.service.impl;
-
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.jk.entity.Userinfo;
- import com.jk.mapper.UserMapper;
- import com.jk.service.UserService;
- import org.springframework.stereotype.Service;
-
- @Service
- public class UserServiceImpl extends ServiceImpl<UserMapper, Userinfo> implements UserService {
-
- }
5.编写MyBatis-plus 分页配置类--MybatisPlusConfig
- package com.jk.conf;
-
- import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- @MapperScan("com.jk.mapper")
- public class MybatisPlusConfig {
- /**
- * 分页插件
- */
- @Bean
- public PaginationInterceptor paginationInterceptor() {
- return new PaginationInterceptor();
- }
- }
6.编写json格式返回工具类--ResultUtil
- package com.jk.utils;
-
- import java.io.Serializable;
-
- /**
- * json格式返回工具类
- */
- public class ResultUtil implements Serializable {
- private Integer code; //返回状态码 0代表成功
- private String msg = ""; //返回提示信息
- private Long count = 0L;
- private Object data; //返回数据
-
- public ResultUtil() {
- super();
- }
-
- public ResultUtil(Integer code) {
- super();
- this.code = code;
- }
-
- public ResultUtil(Integer code, Long count, Object data) {
- this.code = code;
- this.count = count;
- this.data = data;
- }
-
- public ResultUtil(Integer code, String msg) {
- super();
- this.code = code;
- this.msg = msg;
- }
-
- public Integer getCode() {
- return code;
- }
-
- public void setCode(Integer code) {
- this.code = code;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
-
- public Long getCount() {
- return count;
- }
-
- public void setCount(Long count) {
- this.count = count;
- }
-
- public Object getData() {
- return data;
- }
-
- public void setData(Object data) {
- this.data = data;
- }
-
- public static ResultUtil ok() {
- return new ResultUtil(0);
- }
-
- public static ResultUtil ok(Object list) {
- ResultUtil result = new ResultUtil();
- result.setCode(0);
- result.setData(list);
- ;
- return result;
- }
-
- public static ResultUtil ok(String msg) {
- ResultUtil result = new ResultUtil();
- result.setCode(0);
- result.setMsg(msg);
- return result;
- }
-
-
-
- public static ResultUtil error() {
- return new ResultUtil(500, "没有此权限,请联系超管!");
- }
-
- public static ResultUtil error(String str) {
- return new ResultUtil(500, str);
- }
- }
7.编写controller 类--UserController
- package com.jk.controller;
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.jk.entity.Userinfo;
- import com.jk.service.impl.UserServiceImpl;
- import com.jk.utils.ResultUtil;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import java.util.List;
-
- @Controller
- public class UserController {
-
- @Autowired
- private UserServiceImpl userService;
-
- /**
- * 跳转到列表页面
- * @return
- */
- @RequestMapping("/manage/userinfoList")
- public String goList(){
- return "manage/userinfo/userinfoList";
- }
-
- /**
- * 分页条件查询
- * @param page
- * @param limit
- * @param name
- * @param sex
- * @return
- */
- @RequestMapping("/manage/getList")
- @ResponseBody
- public ResultUtil getList(Integer page, Integer limit,String name,String sex){
-
- // 传入分页的属性
- Page<Userinfo> objectPage = new Page<>(page, limit);
- QueryWrapper<Userinfo> wrapper = new QueryWrapper<>();
- // 条件查询:不为空且长度不为0且不由空白符(whitespace) 构成
- wrapper.like(StringUtils.isNotBlank(name),"name",name);
- wrapper.eq(StringUtils.isNotBlank(sex),"sex",sex);
- // 分页查询
- IPage<Userinfo> userinfoIPage = userService.page(objectPage, wrapper);
- // 信息总条数
- long total = userinfoIPage.getTotal();
- // 分页数据
- List<Userinfo> records = userinfoIPage.getRecords();
- // 回写数据
- return new ResultUtil(0,total,records);
-
- }
- }
8.userinfo列表页面:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <c:set var="ctx" value="${pageContext.request.contextPath}"/>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta charset="utf-8">
- <title>用户信息列表</title>
- <meta name="renderer" content="webkit">
- <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
- <meta name="apple-mobile-web-app-status-bar-style" content="black">
- <meta name="apple-mobile-web-app-capable" content="yes">
- <meta name="format-detection" content="telephone=no">
- <link rel="stylesheet" href="${ctx}/static/layui/css/layui.css" media="all"/>
- <link rel="stylesheet" href="${ctx}/static/css/font_eolqem241z66flxr.css" media="all"/>
- <link rel="stylesheet" href="${ctx}/static/css/list.css" media="all"/>
- <script>
- var ctx = "${ctx}"; //js全局项目路径
- </script>
- <style type="text/css">
- </style>
- </head>
- <body class="childrenBody">
- <blockquote class="layui-elem-quote list_search">
-
- <div class="layui-form-item">
- <label class="layui-form-label">姓名</label>
- <div class="layui-input-block" style="margin-left: 0px;">
- <input type="text" name="name" id="name" lay-verify autocomplete="off"
- placeholder="请输入名称"
- class="layui-input" style="display: inline;width: 500px">
- 性别:
- <select name="sex" id="sex" class="layui-select" style="width: 500px">
- <option value="">请选择性别</option>
- <option value="男">男</option>
- <option value="女">女</option>
- </select>
-
- <button class="layui-btn" id="sel">查询</button>
- </div>
- </div>
-
- <div class="layui-inline">
- <a class="layui-btn layui-btn-normal addBtn"><i class="layui-icon"></i> 添加商品信息</a>
- </div>
-
-
- <div class="layui-inline">
- <div class="layui-form-mid layui-word-aux"></div>
- </div>
- </blockquote>
- <!-- 数据表格 -->
- <table id="userinfoList" lay-filter="test"></table>
- <script type="text/javascript" src="${ctx}/static/layui/layui.js"></script>
-
- <script type="text/javascript" src="${ctx}/static/js/common.js"></script>
- <script type="text/javascript" src="${ctx}/static/js/userinfoList.js"></script>
- <script type="text/html" id="barEdit">
- <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="infoDetail">查看</a>
- <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
- <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
- <%-- <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="chongzhi">充值</a>--%>
- </script>
- <script type="text/html" id="tableImg">
- <%--图片显示模板--%>
- <img src="{{d.picurl}}" style="height:48px;width:48px;line-height:48px!important;"/>
- </script>
- <style>
- .layui-table-cell {
- height: 36px;
- line-height: 36px;
- }
- </style>
- </body>
- </html>
8.编写页面对应js文件:
- layui.config({
- base: "js/"
- }).use(['form', 'layer', 'jquery', 'laypage', 'table', 'laytpl'], function () {
- var form = layui.form, table = layui.table;
- layer = parent.layer === undefined ? layui.layer : parent.layer,
- laypage = layui.laypage,
- $ = layui.jquery;
- //数据表格
- table.render({
- id: 'userinfoList',
- elem: '#userinfoList'
- , url: ctx + '/manage/getList' //数据接口
- , cellMinWidth: 80
- , limit: 10//每页默认数
- , limits: [10, 20, 30, 40]
- , cols: [[ //表头
- /*{type: 'checkbox'},*/
- {field: 'id', title: 'ID', width: 60, align: 'center', sort: true},
- {field: 'name', title: '姓名', width: 140, align: 'center'},
- {field: 'phone', title: '电话', width: 140, align: 'center'},
- {field: 'email', title: '邮箱', width: 140, align: 'center'},
- {field: 'picurl', title: '头像', templet: '#tableImg'},
- {field: 'money', title: '金额', width: 140, align: 'center'},
- {field: 'sex', title: '性别', width: 140, align: 'center'},
- {field: 'password', title: '密码', width: 140, align: 'center'},
- {field: 'role', title: '权限', width: 140, align: 'center'},
- {
- field: 'createtime',
- title: '创建时间',
- templet: '<div>{{ formatTime(d.createtime,"yyyy-MM-dd hh:mm:ss")}}</div>'
- },
- {title: '操作', toolbar: '#barEdit'}
- ]]
- , page: true //开启分页
- });
- //监听工具条
- table.on('tool(test)', function (obj) {
- var data = obj.data;
- if (obj.event === 'del') {
- layer.confirm('真的删除行么?', function (index) {
- $.ajax({
- url: ctx + '/manage/deleteUserinfo?id=' + data.id,
- type: "get",
- success: function (d) {
- if (d.code == 0) {
- table.reload('userinfoList', {})
- } else {
- layer.msg("操作失败,请重试", {icon: 5});
- }
- }
- })
- layer.close(index);
- });
- } else if (obj.event === 'edit') {
- var url = ctx + "/manage/editUserinfo?id=" + data.id;//路径拼接
- location.href = url;
- } else if (obj.event === 'chongzhi') {
- var url = ctx + "/manage/chongzhi?id=" + data.id;//路径拼接
- location.href = url;
- }else if (obj.event === 'infoDetail') {
- var url = ctx + "/manage/userinfoInfo?id=" + data.id;
- layer.open({
- type: 2,
- btn: ['关闭'],
- btnAlign: 'c',
- title: "用户信息详情查看",
- skin: 'layui-layer-molv', //加上边框
- area: ['500px', '400px'], //宽高
- shadeClose: true,
- content: url
- });
- }
-
-
- });
-
- //添加用户信息
- $(".addBtn").click(function () {
- var url = ctx + "/manage/addUserinfo";
- location.href = url; //路径跳转
- })
-
- //搜索
- $("#sel").click(function () {
- table.reload('userinfoList', {
- where: {
- name: $("#name").val(),
- sex: $("#sex").val()
- }
- })
- })
-
-
- //批量删除用户信息
- $(".batchDel").click(function () {
- var checkStatus = table.checkStatus('userinfoList')
- , data = checkStatus.data, idsStr = '';
- // layer.alert(JSON.stringify(data));
- if (data.length > 0) {
- $.each(data, function (n, value) {
- idsStr += value.id + ',';
- });
- idsStr = idsStr.substring(0, idsStr.length - 1);
- layer.confirm('真的要删除<strong>' + data.length + '</strong>条数据吗?', function (index) {
- //调用删除接口
- $.ajax({
- url: 'deletesUserinfo?idsStr=' + idsStr,//接口地址
- type: "get",
- success: function (d) {
- if (d.code == 0) {
- //重载表格
- table.reload('userinfoList', {})
- } else {
- layer.msg("删除错误,稍后再试!", {icon: 5});
- }
- }
- })
- layer.close(index);
- });
- } else {
- layer.msg("请选择要操作的数据!");
- }
-
- })
-
- })
最后看下效果:
完结,撒花!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。