首页 > 其他分享 >用mybatis-plus实现分页、多条件查询

用mybatis-plus实现分页、多条件查询

时间:2023-02-17 17:13:57浏览次数:30  
标签:分页 查询 plus new mybatis import com Page page1

mybatis-plus
条件构造器QueryWrapper常用方法

/**
  *附加条件构造器QueryWrapper常用方法 ---这几个肯定够用了
  */
 wrapper.eq("数据库字段名", "条件值"); 				  //相当于where条件
 wrapper.between("数据库字段名", "区间一", "区间二");	//相当于范围内使用的between
 wrapper.like("数据库字段名", "模糊查询的字符"); 	    //模糊查询like
 wrapper.groupBy("数据库字段名");  					//相当于group by分组
 wrapper.in("数据库字段名", "包括的值,分割"); 			//相当于in
 wrapper.orderByAsc("数据库字段名");					 //排序升序
 wrapper.orderByDesc("数据库字段名");					 //排序降序
 wrapper.ge("数据库字段名", "要比较的值");				 //大于等于
 wrapper.le("数据库字段名", "要比较的值");				 //小于等于

  

一、分页查询

1.设置分页信息

//1.设置分页信息
Page<User> page = new Page<>(1,10); 

2.写配置类(config/MyBatisPlusConfig)

package com.fzy.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

        // 最新版
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }

}

3.查询

package com.fzy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fzy.entity.User;
import com.fzy.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    //分页查询
    @RequestMapping("/page")
    public IPage<User> page(){
        //1.设置分页信息
        Page<User> page = new Page<>(2,3);

        //2.查询
        Page<User> page1 = userService.page(page);
        System.out.println("page1 = " + page1);
        System.out.println("page1.getSize() = " + page1.getSize());
        System.out.println("page1.getCurrent() = " + page1.getCurrent());
        System.out.println("page1.getPages() = " + page1.getPages());
        System.out.println("page1.getTotal() = " + page1.getTotal());
        System.out.println("page1.getRecords() = " + page1.getRecords());
        return page1;
    }
}

二、多表分页+条件查询

1.设置分页信息,和查询条件

    //多表分页+条件查询
    @RequestMapping("/list3")
    public Page<UserAndDeptVo>  list3(){
        //设置分页信息
        Page<UserAndDeptVo> page = new Page<>(1, 5);

        //设置查询条件
        User user = new User(){{
            setUsername("冬冬");
        }};
      
        //查询
        Page<UserAndDeptVo> pageInfo = userService.findUserAndDeptByPage(page,user);

        System.out.println("pageInfo.getTotal() = " + pageInfo.getTotal());
        System.out.println("pageInfo.getSize() = " + pageInfo.getSize());
        System.out.println("pageInfo.getPages() = " + pageInfo.getPages());
        return pageInfo;
    }

2.写配置类(config/MyBatisPlusConfig)

package com.fzy.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

        // 最新版
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        }

}

3.封装类

package com.fzy.vo;

import com.fzy.entity.Department;
import com.fzy.entity.User;
import lombok.Data;

@Data
public class UserAndDeptVo {

    private User user;
    private Department department;
}

4.编写动态sql,映射

Page<UserAndDeptVo> selectUserAndDeptByPage(@Param("page") Page<UserAndDeptVo> page,@Param("user") User user);

  

<?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="com.fzy.mapper.UserMapper">

    <sql id="Base_Column_List">
        id,username,password,
        dept_id,is_delete,pro_img
    </sql>

    <resultMap id="UserAndDeptVo" type="com.fzy.vo.UserAndDeptVo">
        <association property="user" javaType="com.fzy.entity.User">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="username" column="username" jdbcType="VARCHAR"/>
            <result property="password" column="password" jdbcType="VARCHAR"/>
            <result property="deptId" column="dept_id" jdbcType="VARCHAR"/>
            <result property="isDelete" column="is_delete" jdbcType="INTEGER"/>
            <result property="proImg" column="pro_img" jdbcType="VARCHAR"/>
        </association>
        <association property="department" javaType="com.fzy.entity.Department">
            <id property="deptId" column="dept_id" jdbcType="VARCHAR"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
        </association>
    </resultMap>

	//分页连表查询
    <select id="selectUserAndDeptByPage" resultMap="UserAndDeptVo">
        SELECT     u.*,d.*
        FROM `user` u
        LEFT JOIN `departments` d
        ON u.dept_id=d.dept_id
        <where>
            <if test="user!=null and user!=''">
                u.username=#{user.username}
            </if>
        </where>
    </select>

</mapper>

分页+条件查询

    @Override
    public PageApiRest getList(PageDTO<SysPermission> pageDto) {

        //1.设置分页信息
        IPage<SysPermission> page = new Page<>(pageDto.getPage(),pageDto.getSize());

        //2.设置查询条件
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        //查询条件不为空,并且标题不为空串,就模糊查询标题
        //资源名称
        if(pageDto.getWhere()!=null && !StringUtils.isEmpty(pageDto.getWhere().getPermName())){
            queryWrapper.lambda().like(SysPermission::getPermName,pageDto.getWhere().getPermName());
        }
        //资源路径
        if(pageDto.getWhere()!=null && !StringUtils.isEmpty(pageDto.getWhere().getLinkUrl())){
            queryWrapper.lambda().like(SysPermission::getLinkUrl,pageDto.getWhere().getLinkUrl());
        }
        //资源分类
        if(pageDto.getWhere()!=null && !StringUtils.isEmpty(pageDto.getWhere().getPermDesc())){
            queryWrapper.lambda().like(SysPermission::getPermDesc,pageDto.getWhere().getPermDesc());
        }

        //3.查询
        IPage<SysPermission> page1 = baseMapper.selectPage(page, queryWrapper);


        //4.封装,返回
        PageApiRest<SysPermission> pageRest = new PageApiRest<>();
        pageRest.setTotal(page1.getTotal());
        pageRest.setData(page1.getRecords());

        return pageRest;
    }

三、mybatis-plus的修改时间自动填充

1.时间字段上配置注解

@TableField(fill = FieldFill.INSERT)	//插入时生效
private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)		//插入和修改时生效
private Date updateTime;

2.编写配置类(MyMetaObjectHandler.java)

package com.fzy.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐使用)

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // 起始版本 3.3.0(推荐)

    }
}

  

标签:分页,查询,plus,new,mybatis,import,com,Page,page1
From: https://www.cnblogs.com/lhm166/p/17130831.html

相关文章

  • Django Paginatior分页,页码过多,动态返回页码,页码正常显示
    问题:当返回数据较多,如设置每页展示10条,数据接近200条,返回页码范围1~20,前端每个页码都显示的话,就会出现页码超出当前页面,被遮挡的页码无法操作和显示不美观;代码优化:在使......
  • 把流氓 QQ 装进 Sanboxie-Plus
     利用开源Sandboxie-Plus为Windows桌面程序创建隔离沙箱环境守护隐私保持系统干净整洁  ......
  • ant-design-vue的a-table组件分页功能实现(原创前端若水)
    <a-table:pagination="myCustomerTablePageConfig"@change="myCustomerTablePageChange"></a-table>data(){return{//......
  • JavaEE_使用mybatis从数据库中获取分页数据,并在web端显示
    idea+servlet+jsp+jstl+mysql+mybatis。    一、准备数据库数据表(数据)二、准备数据对象(pojo),创建对象set/get方法2.1单个数据对象2.2页内数据对象......
  • mybatis使用
    查询问题方式一:LambdaQueryWrapper<Tenant>wrapper=newLambdaQueryWrapper<>();wrapper.like(Func.isNotEmpty(tenantPage.getTenantName()),Tenant::getTenantNam......
  • Mybatis-ResultHandler
    Mybatis接口——ResultHandlermybatis中的ResultHandler主要有2个作用:对取出的结果进行统一处理配合defaultFetchSize解决oom问题那如何使用这个接口呢?首先,......
  • MyBatis、LogBack XML文件模板
    xxxMapper模板<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper......
  • MybatisPlus之LambdaQueryWrapper简单用法
    简单查询(推荐)LambdaQueryWrapper<User>wrapper=newLambdaQueryWrapper<>();wrapper.eq(User::getUserId,id);wrapper.like(User::getUserName,userName);List......
  • SqlServer 分页查询
    转载于 https://www.bbsmax.com/A/ZOJPDNQ2Jv/ 第一种方法:效率最高SELECTTOP页大小*FROM(SELECTROW_NUMBER()OVER(ORDERBYid)ASRowNumber,*FROMtable1......
  • python urlencode()改为quote_plus()
    使用对拼接的字符串,以字典的格式传入加密fromurllib.parseimporturlencodebase_url="https://m.weibo.cn/api/container/getIndex?"params1={"value":"english......