1.添加分頁插件
在mybatis-generator-config.xml添加plugin節點:
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin>
2.在maven面板重新運行mybatis-generator:generate自動生成了分頁相關的內容。
ProductMapper.java添加了分頁查詢方法:
List<Product> selectByExampleWithRowbounds(ProductExample example, RowBounds rowBounds);
ProductMapper.xml添加了SelectByExampleWithRowbounds節點:
<select id="selectByExampleWithRowbounds" parameterType="com.data.pojo.ProductExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from product <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select>
3.測試
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml") @RunWith(SpringJUnit4ClassRunner.class) public class ProductDaoTests { @Resource ProductMapper productMapper; @Test public void test_selectByPrimaryKey(){ Product product=productMapper.selectByPrimaryKey(1); System.out.println(product.getName()); } @Test public void test_page(){ int id=2; int pageIndex=1,pageSize=3; RowBounds rowBounds=new RowBounds((pageIndex-1)*pageSize,pageSize); List<Product> products=productMapper.selectByExampleWithRowbounds(new ProductExample(),rowBounds); if(products==null){ System.out.println("查詢結果為空"); }else { System.out.println("第"+pageIndex+"頁,每頁大小"+pageSize); for(Product p:products){ System.out.println("id="+p.getId()+" name="+p.getName()); } } } }
源碼:http://pan.baidu.com/s/1bpJ2pJp