Mybatis分页插件

一、导入相关依赖

<!--mybatis分页插件相关依赖-->
<dependency> 
    <groupId>com.github.pagehelper</groupId> 
    <artifactId>pagehelper</artifactId> 
    <version>3.7.5</version>
</dependency>  
<dependency> 
    <groupId>com.github.jsqlparser</groupId> 
    <artifactId>jsqlparser</artifactId> 
    <version>1.1</version> 
</dependency> 

二、Mybatis配置文件配置插件

applicationContext.xml

<!--配置 mybatis 的分页插件;--> 
<property name="plugins"> 
    <array> 
        <bean class="com.github.pagehelper.PageHelper"> 
            <property name="properties"> 
                <value> dialect=mysql </value> 
            </property> 
        </bean> 
    </array> 
</property>

三、定义一个通用的分页PageBean

PageBean.java

public class PageBean<T> {
    private long total; //所有记录行数
    private List<T> rows;//当前页的数据
    private int pageSize = 2;//每页2条
    private int pageTotals = 0;//一共多少页
    private int pageIndex = 1; //第几页,默认第一页

    public PageBean() {
    }

    public PageBean(long total, List<T> rows, int pageSize, int pageTotals, int pageIndex){
        this.total = total;
        this.rows = rows;
        this.pageSize = pageSize;
        this.pageTotals = pageTotals;
        this.pageIndex = pageIndex;
    }

}

四、Service层

@Service
public class TUserServiceImpl implements ITUsersService {

    @Autowired
    private TUsersMapper tUsersMapper;

    @Override
    public PageBean<TUsers> getAllUsersAndRoles(int index) {
        //开始分页,默认每页两条数据
        PageHelper.startPage(index,2);
        List<TUsers> rows = tUsersMapper.getAllUsersAndRoles();
        Page<TUsers> plist = (Page<TUsers>) rows;
        PageBean<TUsers> pb = new PageBean<>(
                plist.getTotal(),
                plist.getResult(),
                plist.getPageSize(),
                plist.getPages(),
                plist.getPageNum()
        );
        return pb;
    }
}

五、controller层

@Controller
@RequestMapping("/users")
public class TUsersController {

    @Autowired
    private ITUsersService itUsersService;

    @RequestMapping("/list")
    public String getAllUsersAndRoles(Model model,@RequestParam(required = true,defaultValue = "1") int index) {
        model.addAttribute("pb", itUsersService.getAllUsersAndRoles(index));
        return "/users/list";
    }
}

六、页面显示

<tr>
    <td colspan="5">
        <ul class="pagination">
            <c:forEach begin="1" end="${pb.pageTotals}" var="p" step="1">
                <li>
                    <a href="/users/list.action?index=${p}">${p}</a>
                </li>
            </c:forEach>
        </ul>
    </td>
</tr>

分页展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值