Springboot+Mybatis实现分页加条件查询

User.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="com.shelbourne.schooldelivery.mapper.UserMapper">
<!--    用户更新-->
    <update id="update">-- 这里的id为函数名
        update user
        <set>
            <if test="username != null and username !=''">
                username=#{username},
            </if>
            <if test="nickname != null and nickname !=''">
                nickname=#{nickname},
            </if>
            <if test="email != null and email !=''">
                email=#{email},
            </if>
            <if test="phone != null and phone !=''">
                phone=#{phone},
            </if>
            <if test="address != null and address !=''">
                address=#{address}
            </if>
        </set>
        <where>
            id = #{id}
        </where>
    </update>

<!--    分页+条件查询-->
    <select id="selectPageWithParam" resultType="com.shelbourne.schooldelivery.entity.User">
        select * from user
        <include refid="condition"></include>
        limit #{startIdx},#{size}
    </select>

<!--    查询满足条件的用户总数-->
    <select id="selectTotalWithParam" resultType="java.lang.Integer">
        select count(*) from user
        <include refid="condition"></include>
    </select>

<!--    查询条件-->
    <sql id="condition">
        <where>
            1=1
            <if test="username != null and username != ''">
                and username like concat("%",#{username},"%")
            </if>
            <if test="email != null and email != ''">
                and email like concat("%",#{email},"%")
            </if>
            <if test="address != null and address != ''">
                and address like concat("%",#{address},"%")
            </if>
        </where>
    </sql>
</mapper>

UserMapper.java

package com.shelbourne.schooldelivery.mapper;

import com.shelbourne.schooldelivery.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    //查询所有用户
    @Select("select * from user")
    //mybatis提供注解,注意SQL语句后不能加分号
    List<User> findAll();

    //新增用户
    @Insert("insert into user(username,password,nickname,email,phone,address)" +
            "values(#{username},#{password},#{nickname},#{email},#{phone},#{address})")
    public Integer insert(User user);

    //通过注解(静态)和xml里面(动态)两种方式编写SQL语句
    int update(User user);

    //删除单个用户
    @Delete("delete from user where id=#{id}")
    Integer deleteById(@Param("id") Integer id);//最后加上@Param参数,参数名和上面的#{}里面的一样

    //查询记录条数
    @Select("select count(*) from user")
    Integer selectTotal();

    //编写动态SQL实现分页查询+条件查询
    //查询满足条件的某一页用户
    List<User> selectPageWithParam(Integer startIdx, Integer size, String username, String email, String address);

    //查询满足条件的所有用户数
    int selectTotalWithParam(String username, String email, String address);
}

UserController.java

package com.shelbourne.schooldelivery.controller;

import com.shelbourne.schooldelivery.entity.User;
import com.shelbourne.schooldelivery.mapper.UserMapper;
import com.shelbourne.schooldelivery.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")  //统一给接口加前缀,postman后台接口localhost:9090/user
@RestController
public class UserController {

    @Autowired  //注入其他类的注解
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    //查询所有用户
    @GetMapping
    public List<User> findAll(String username) {
        return userMapper.findAll();
    }

    //通过POST请求进行新增和更新操作
    @PostMapping
    public Integer save(@RequestBody User user) {//一定要加上RequestBody,可以把前端传回的JSON对象转换为Java对象
        return userService.save(user);
    }

    //删除请求接口
    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id) {//这里的“id”必须和DeleteMapping里面的名字一样
        return userMapper.deleteById(id);
    }

    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String username,
                                        @RequestParam String email, @RequestParam String address) {
        int startIdx = (pageNum - 1) * pageSize, size = pageSize;
        List<User> data = userMapper.selectPageWithParam(startIdx, size, username, email, address);//获取一页的数据
        int total = userMapper.selectTotalWithParam(username, email, address);//查询总条数
        Map<String, Object> res = new HashMap<>();
        res.put("data", data);//表格数据
        res.put("total", total);//分页使用
        return res;
    }
}

Home.vue中:

<script>
    export default {
        data() {
            return {
                total: 0,//记录条数为0
                pageNum: 1,//默认从第一条记录开始
                pageSize: 10,//默认分页大小为10
                username: "",//条件查询的姓名
                email: "",//条件查询的邮箱
                address: "",//条件查询的地址
            }
        },
        created() {//页面渲染完成后的数据刷新
            this.flushData()
        },
        methods: {
            //获取数据
            flushData() {
                fetch("http://localhost:9090/user/page?pageNum=" +
                    this.pageNum + "&pageSize=" + this.pageSize + "&username=" +
                    this.username + "&email=" + this.email + "&address=" + this.address).then(res => res.json()).then(res => {
                    // console.log(res)
                    //跨域问题:前端端口8080,后端端口9090,导致跨域
                    this.tableData = res.data
                    this.total = res.total
                })
            }
        }
    }
</script>

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot项目中使用MyBatis进行分页查询,你可以按照以下步骤进行操作: 1. 首先,确保你的Spring Boot项目中已经引入了MyBatis的相关依赖。可以在你的pom.xml文件中添以下依赖: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>latest_version</version> </dependency> ``` 2. 创建一个Mapper接口,用于定义分页查询的方法。例如: ```java import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserMapper { List<User> getUsersByPage(int offset, int limit); } ``` 3. 在对应的Mapper XML文件中编写SQL语句,使用数据库的分页功能。例如,使用MySQL的LIMIT语句来实现分页查询: ```xml <select id="getUsersByPage" resultType="User"> SELECT * FROM user LIMIT #{offset}, #{limit} </select> ``` 其中,`offset`表示查询的起始位置,`limit`表示每页返回的记录数。 4. 在Service层或者Controller层中调用Mapper接口的方法进行分页查询。可以使用PageHelper或者手动计算分页参数。 使用PageHelper插件的示例代码如下: ```java import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> getUsersByPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<User> userList = userMapper.getUsersByPage(); PageInfo<User> pageInfo = new PageInfo<>(userList); return pageInfo.getList(); } } ``` 手动计算分页参数的示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> getUsersByPage(int pageNum, int pageSize) { int offset = (pageNum - 1) * pageSize; return userMapper.getUsersByPage(offset, pageSize); } } ``` 这样就可以在Spring Boot项目中使用MyBatis进行分页查询了。 希望对你有所帮助!如果还有其他问题,请继续提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值