Mysql+Mybatis分页查询

Mysql+Mybatis分页查询一,首先做一个查询所有并显示daopublicinterfaceProductDAO{ publicList<Product>list();}mapper<mappernamespace="hust.mm.dao.ProductDAO"> <selectid="list"resultType="Product"> s..

大家好,又见面了,我是你们的朋友全栈君。

一,首先做一个查询所有并显示

dao

public interface ProductDAO {
	public List<Product> list();
}

mapper

<mapper namespace="hust.mm.dao.ProductDAO">
	<select id="list" resultType="Product">
		select * from product
	</select>
</mapper>

controller

@RequestMapping("/list.do")
public ModelAndView productlist(){
	ModelAndView mav = new ModelAndView();
		
	List<Product> products = productDao.list();
		
	mav.addObject("products", products);
	mav.setViewName("productList");
		
	return mav;
}

jsp

<table align="center">
		<th>
			<td>id</td>
			<td>name</td>
			<td>price</td>
		</th>
		<c:forEach items="${products }" var="p" varStatus="st">
			<tr>
				<td>${p.id }</td>
				<td>${p.name }</td>
				<td>${p.price }</td>
			</tr>
		</c:forEach>
</table>

以上简要给出了一个表中的所有数据

二,分页显示

修改dao

public interface ProductDAO {
	public List<Product> list();
	public List<Product> list(@Param("start") int start, @Param("count") int count);
}

修改mapper

<mapper namespace="hust.mm.dao.ProductDAO">
    <select id="list" resultType="Product">
		select * from product
		<if test="start!=null and count!=null">
			limit #{start},#{count}
		</if>
	</select>
</mapper>

修改controller

@RequestMapping("/list.do")
public ModelAndView productlist(int start){
	ModelAndView mav = new ModelAndView();
		
	List<Product> products = productDao.list(start,3);
		
	mav.addObject("products", products);
	mav.addObject("start", start);
	mav.setViewName("productList");
		
	return mav;
}

修改jsp

<table align="center">
		<th>
			<td>id</td>
			<td>name</td>
			<td>price</td>
		</th>
		<c:forEach items="${products }" var="p" varStatus="st">
			<tr>
				<td>${p.id }</td>
				<td>${p.name }</td>
				<td>${p.price }</td>
			</tr>
		</c:forEach>
        
        <tr>
			<td><a href="list.do?start=${start-3 }">上一页</a></td>
			<td><a href="list.do?start=${start+3 }">下一页</a></td>
		</tr>
</table>

这里以每页三条数据分页显示

三,完善分页

可以想到,当在首页点击上一页和在尾页点击下一页,应该没有反应或者做出相应处理。有两种解决方案,

  1. 使用jstl或el语句判断start参数是否小于0或大于total-分页大小
  2. 在controller对start进行判断

四,分页的其他方案

上述的分页是利用了mybatis的动态SQL以及MySQL数据库特有的limit语句。有一定的特殊性,可以使用PageHelper这一类分页插件来进行分页开发。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/137181.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号