Mybatis分页通过limit字段实现

在分页查询时,在前端时会需要页面的各种参数,比如说:页数,页面的大小,总页数,所以不能再使用List返回查询结果。需要自定义一个Page对象包含这些信息进行返回

/**
 * @page 分页起始页
 * @size 每页的数据量
 * @rows 返回结果集
 *@total 记录条数、
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Pager<Student> {
    private int page;
    private int size;
    private List<Student> rows;
    private long total;
}

Mapper

@Mapper
public interface StudentMapper {
	//Map中的字段是limit语句所需要的偏移量与size
    public List<Student> findByPager(Map<String,Object> params);
	
    public long count();

}

Mapper.xml

在这里需要对page对象处理过后再传入数据库查询,可以在service层通过size进行计算

  <select id="findByPager" resultType="com.lxp.domain.Student">
        select *
        from tb_student
        limit #{page},#{size}
    </select>

    <select id="count" resultType="Long">
        select count(1) from tb_student
    </select>

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyBatisTest {

    @Autowired
    StudentMapper studentMapper;
    @Test
    public void find(){
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("page",1);
        map.put("size",5);
        Pager<Student> pager=new Pager<Student>();
        List<Student> list=studentMapper.findByPager(map);
        pager.setRows(list);
        pager.setTotal(studentMapper.count());
        System.out.println(pager);

    }
  }

版权声明:本文为qq_43144825原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。