在使用Mybatis进行分页操作时,比较常用用PageHelper这个插件来做分页的,可是这个插件相对来说配置还是比较繁复而且很多功能其实项目中是用不到的。虽然PageHelper提供了多数据库支持,可国内大多数项目还是以MySQL数据库为主,所以想到利用MyBatis Generator提供的插件拓展来生成相应limit语句实现Mysql的分页功能。具体使用和实现可以参照开源项目
1.增加Maven依赖;
com.itfsw
mybatis-generator-plugin
1.0.5
2.在MyBatis Generator插件配置文件中添加插件;
3.插件使用;
public class TbExample {
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
protected Integer offset;
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
protected Integer rows;
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
*
* @mbg.generated
* @author hewei
*/
public TbExample limit(Integer rows) {
this.rows = rows;
return this;
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
*
* @mbg.generated
* @author hewei
*/
public TbExample limit(Integer offset, Integer rows) {
this.offset = offset;
this.rows = rows;
return this;
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
public TbExample page(Integer page, Integer pageSize) {
this.offset = page * pageSize;
this.rows = pageSize;
return this;
}
// offset 和 rows 的getter&setter
// 修正了clear方法
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
rows = null;
offset = null;
}
}
public class Test {
public static void main(String[] args) {
this.tbMapper.selectByExample(
new TbExample()
.createCriteria()
.andField1GreaterThan(1)
.example()
.limit(10) // 查询前10条
.limit(10, 10) // 查询10~20条
.page(1, 10) // 查询第2页数据(每页10条)
);
}
}