MyBatis Plus 自定义 SQL 分页查询实现

MyBatis Plus 自定义 SQL 分页查询实现

要在 MyBatis Plus 中实现自定义 SQL 的分页查询并增加创建时间范围条件,你需要做以下几个步骤:

1. 修改 Mapper XML 文件

首先更新你的 SQL 查询,添加时间范围条件:

<select id="getGroup" resultType="java.util.Map">
    SELECT work_group_name AS name,0 as 'lottery',count(1) as 'promoter' 
    FROM member_promoter_relation 
    where work_group_name is not null 
    <if test="startTime != null">
        AND create_time >= #{startTime}
    </if>
    <if test="endTime != null">
        AND create_time &lt;= #{endTime}
    </if>
    GROUP BY work_group_name
    
    UNION all
    
    SELECT work_group_name AS name,count(1) as 'lottery',0 as 'promoter' 
    FROM member_lottery_records 
    where work_group_name is not null 
    <if test="startTime != null">
        AND create_time >= #{startTime}
    </if>
    <if test="endTime != null">
        AND create_time &lt;= #{endTime}
    </if>
    GROUP BY work_group_name
</select>

2. 创建 Mapper 接口

在 Mapper 接口中添加对应方法:

public interface YourMapper extends BaseMapper<YourEntity> {
    IPage<Map<String, Object>> getGroup(Page<?> page, 
                                       @Param("startTime") Date startTime, 
                                       @Param("endTime") Date endTime);
}

3. 在 Service 层调用

在 Service 实现中调用该方法:

@Service
public class YourServiceImpl implements YourService {
    
    @Autowired
    private YourMapper yourMapper;
    
    @Override
    public IPage<Map<String, Object>> getGroupPage(int current, int size, Date startTime, Date endTime) {
        Page<Map<String, Object>> page = new Page<>(current, size);
        return yourMapper.getGroup(page, startTime, endTime);
    }
}

4. 在 Controller 层使用

@RestController
@RequestMapping("/api/group")
public class GroupController {
    
    @Autowired
    private YourService yourService;
    
    @GetMapping("/page")
    public Result getGroupPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        
        IPage<Map<String, Object>> page = yourService.getGroupPage(current, size, startTime, endTime);
        return Result.success(page);
    }
}

注意事项

  1. 确保你的 SQL 查询支持分页,MyBatis Plus 会自动将分页参数添加到查询中
  2. 时间范围条件使用了 <if> 标签,这样当参数为 null 时不会添加该条件
  3. 在 Controller 中使用了 @DateTimeFormat 注解来格式化日期参数
  4. 如果你的数据库字段名不是 create_time,请相应调整 SQL 语句

如果你使用的是 XML 方式实现分页,可能需要在 SQL 中添加分页参数,但对于 MyBatis Plus 来说,通常不需要手动添加,框架会处理分页逻辑。

posted @ 2025-06-25 15:21  VipSoft  阅读(840)  评论(0)    收藏  举报