spingboot+mybatis分页(limit分页)--R

controller参数 继承分页类:

package com.finance.cmp.ruleEngine.common.vo;

public class BaseQueryVo {
    public boolean _search;
    public String nd;
    public String sidx;
    public String sord;
    public Integer page;
    public Integer rows;

    public boolean is_search() {
        return _search;
    }

    public void set_search(boolean _search) {
        this._search = _search;
    }

    public String getNd() {
        return nd;
    }

    public void setNd(String nd) {
        this.nd = nd;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public Integer getPage() {
        if (page == null) {
            return 1;
        }
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        if (rows == null) {
            return 20;
        }
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}

1.controller: 可不传参数,传参数(条件/rows/page)

@GetMapping("list")
    public Result selectList(RuleQueryVo ruleQueryVo) {
        log.info("入参:" + ruleQueryVo);
        Map<String, Object> resultMap = null;
        try {
            resultMap = itRuleService.selectByList(ruleQueryVo);
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.SERVER_ERROR, e.getMessage());
        }
        return ResultUtil.success(resultMap);
    }

2.service:
接口:

public interface ITVarBasicService {

    int getBasicIsUse(Integer factorVarId);

     //分页
    List<TVarBasic> getAll();

    List<TVarBasic> getAllValidFromCache();

    TVarBasic getByOne(TVarBasic tVarBasic);

    Map<String, Object> selectByList(VarBasicQueryVo vo);

    Integer insertTVarBasic(TVarBasic tVarBasic);

    Integer deleteTVarBasic(int id);

    Integer updateTVarBasic(TVarBasic tVarBasic);

}

实现类:

package com.finance.cmp.ruleEngine.service.service.impl;

import com.finance.cmp.ruleEngine.cache.content.Constant;
import com.finance.cmp.ruleEngine.common.vo.RuleQueryVo;
import com.finance.cmp.ruleEngine.dao.mapper.TRuleMapper;
import com.finance.cmp.ruleEngine.dao.model.TRule;
import com.finance.cmp.ruleEngine.dao.model.TScoreCard;
import com.finance.cmp.ruleEngine.dao.model.TValConst;
import com.finance.cmp.ruleEngine.dao.vo.DeriveVo;
import com.finance.cmp.ruleEngine.dao.vo.RuleVo;
import com.finance.cmp.ruleEngine.service.common.RedisCacheService;
import com.finance.cmp.ruleEngine.service.service.ITRuleService;
import com.finance.cmp.ruleEngine.service.util.AcStringUtils;
import com.finance.cmp.ruleEngine.service.util.MapUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

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

@SuppressWarnings("all")
@Log4j
@Service
public class TRuleServiceImpl implements ITRuleService {

    @Autowired
    private TRuleMapper tRuleMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    @Override
    public TRule selectById(Integer id) {
        Map<String, Object> temMap = new HashMap<>();
        temMap.put("id", id);
        TRule tRule = tRuleMapper.selectById(temMap);
        return tRule;
    }

    @Override
    public List<TRule> getAllValidFromCache() {
        List<TRule> lst;
        if (redisCacheService.hasKey(Constant.REDIS_CONSOLE_RULE_ALL)) {
            lst = (List<TRule>) redisCacheService.get(Constant.REDIS_CONSOLE_RULE_ALL);
        } else {
            lst = tRuleMapper.getAllValid();
            redisCacheService.set(Constant.REDIS_CONSOLE_RULE_ALL, lst);
        }
        return lst;
    }

    @Override
    public Integer ruleIsUse(Integer ruleId) {
        Map<String, Object> temMap = new HashMap<>();
        temMap.put("ruleId", ruleId);
        return tRuleMapper.ruleIsUse(temMap);
    }

    @Override
    public int getTotalRuleList(String varName) {
        Map<String, Object> temMap = new HashMap<>();
        temMap.put("name", varName);
        return tRuleMapper.getTotalRuleList(temMap);
    }

    //分页 逻辑
    
    @Override
    public Map<String, Object> selectByList(RuleQueryVo vo) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> temMap = new HashMap<>();
        temMap = MapUtils.beanToMap(vo, Constant.LIST_FIELD);
        //查询总条数
        int totalNum = tRuleMapper.getTotalRuleList(temMap);
        log.info("总条数为:" + totalNum);
        if (totalNum < 1) {
            resultMap.put("total", 0);
            resultMap.put("data", null);
            return resultMap;
        }

        String pageIndex = vo.getPage().toString();
        String pageSize = vo.getRows().toString();
        temMap.put("start", 0);
        temMap.put("size", 10);
        if ((!AcStringUtils.isEmpty(pageIndex)) && (!AcStringUtils.isEmpty(pageSize))) {
            int start = ((Integer.parseInt(pageIndex)) - 1) * (Integer.parseInt(pageSize));
            int size = Integer.parseInt(pageSize);
            // int
            // end=((Integer.parseInt(pageIndex)))*(Integer.parseInt(pageSize));
            temMap.put("start", start);
            temMap.put("size", size);
        }
        //分页按条件
        List<TRule> dataList = tRuleMapper.getRuleList(temMap);
        resultMap.put("pageIndex", pageIndex);
        resultMap.put("totalPages"
                , (totalNum % Integer.parseInt(pageSize) > 0
                        ? totalNum / Integer.parseInt(pageSize) + 1
                        : totalNum / Integer.parseInt(pageSize)
                )
        );
        resultMap.put("total", totalNum);
        resultMap.put("data", dataList);
        return resultMap;
    }

    @Override
    public TRule selectByRuleName(TRule tRule) {
        return tRuleMapper.selectOne(tRule);
    }

    @Override
    public Integer insertRule(TRule tRule) {
        int addRule = tRuleMapper.insert(tRule);
        if (addRule > 0) {
            redisCacheService.delete(Constant.REDIS_CONSOLE_RULE_ALL);
        }
        return addRule;
    }

    @Override
    public Integer deleteRule(int id) {
        int deleteRule = tRuleMapper.deleteByPrimaryKey(id);
        if (deleteRule > 0) {
            redisCacheService.delete(Constant.REDIS_CONSOLE_RULE_ALL);
        }
        return deleteRule;
    }

    @Override
    public Integer updateRule(TRule tRule) {
        //多条件查询
        Example example = new Example(TRule.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", tRule.getId());
        Date dt = tRule.getUpdateTime();
        criteria.andEqualTo("updateTime", dt);
        tRule.setUpdateTime(new Date());
        int update = tRuleMapper.updateByExampleSelective(tRule, example);
        if (update > 0) {
            redisCacheService.delete(Constant.REDIS_CONSOLE_RULE_ALL);
        }
        return update;
    }
}

3.mapper:

public interface TVarBasicMapper extends MyMapper<TVarBasic> {


    int getBasicIsUse(Map<String, Object> temMap);

    //查总条数 不分页
    int getTotalVarBasicList(Map<String, Object> temMap);

    //分页
    List<TVarBasic> getVarBasicList(Map<String, Object> temMap);

    List<TVarBasic> getAllValid();

}

4.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.finance.cmp.ruleEngine.dao.mapper.TVarBasicMapper">
    <resultMap id="BaseResultMap" type="com.finance.cmp.ruleEngine.dao.model.TVarBasic">
        <!--
          WARNING - @mbg.generated
        -->
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="var_name" jdbcType="VARCHAR" property="varName"/>
        <result column="var_caption" jdbcType="VARCHAR" property="varCaption"/>
        <result column="var_sourceType" jdbcType="VARCHAR" property="varSourcetype"/>
        <result column="var_sourceRestful" jdbcType="VARCHAR" property="varSourcerestful"/>
        <result column="var_sourceVar" jdbcType="VARCHAR" property="varSourcevar"/>
        <result column="status" jdbcType="VARCHAR" property="status"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
    </resultMap>

    <select id="getTotalVarBasicList" parameterType="map" resultType="int">
        SELECT COUNT(1) FROM t_var_basic
        where 1=1
        <if test="varName != null and varName != '' ">
            and var_name = #{varName}
        </if>
        <if test="varCaption != null and varCaption != '' ">
            and var_caption = #{varCaption}
        </if>
        <if test="varSourcetype != null and varSourcetype != '' ">
            and var_sourceType = #{varSourcetype}
        </if>
    </select>

    <select id="getVarBasicList" parameterType="map" resultMap="BaseResultMap">
        SELECT * FROM t_var_basic
        where 1=1
        <if test="varName != null and varName != '' ">
            and var_name = #{varName}
        </if>
        <if test="varCaption != null and varCaption != '' ">
            and var_caption = #{varCaption}
        </if>
        <if test="varSourcetype != null and varSourcetype != '' ">
            and var_sourceType = #{varSourcetype}
        </if>
        <if test="start != null ">
            LIMIT #{start}, #{size}
        </if>
    </select>

    <select id="getBasicIsUse" parameterType="map" resultType="int">
        SELECT COUNT(0) FROM DUAL WHERE EXISTS (
        select factor_var_id FROM t_var_derive_factor D WHERE D.factor_var_type = 'BASIC' AND D.factor_var_id = #{factorVarId}
        UNION ALL
        SELECT factor_var_id FROM t_var_statistical_factor S WHERE S.factor_var_type = 'BASIC' AND S.factor_var_id = #{factorVarId}
        UNION ALL
        SELECT factor_var_id FROM t_rule_factor R WHERE R.factor_var_type = 'BASIC' AND R.factor_var_id = #{factorVarId}
        UNION ALL
        SELECT 1 FROM t_score_card_flow scf WHERE scf.item_type = 'BASIC' AND scf.item_id = #{factorVarId}
        UNION ALL
        SELECT 1 FROM t_score_card_item_value sciv WHERE sciv.if_item_type = 'BASIC' AND sciv.if_item_value = #{factorVarId}
        )
    </select>

    <select id="getAllValid" resultMap="BaseResultMap">
        SELECT * FROM T_VAR_BASIC WHERE `STATUS` = 'valid'
    </select>

</mapper>

至此分页完成。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在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进行分页查询了。 希望对你有所帮助!如果还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值