一、分页问题
MyBatis自动生成代码没有分页功能。
如:
public class User {private Integer userId;private String name;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}pubilc class Test{public static void main(String[] args){UserExample user= new UserExample();user.createCriteria().andNameLike("%" + "zhansan" + "%");user.setOrderByClause("user_id asc");List<User> uList = userMapper.selectByExample(user);}}
二、解决方案
1、改写selectByExample方法和XML,增加分页字段;具有侵入性,下一次自动生成代码失效
2、新增分页查询@Select注解方法;需要额外的Mapper基接口
public interface UserMapper extends UserBaseMapper {
//... generate method
}public interface UserBaseMapper {@Select({"<script>","select u.user_id as userId, u.user_name as `name` ","from user u ","where 1=1 ","<if test=\"u!=null\"> "," <if test=\"u.userId!=null\"> "," and u.user_id=#{u.userId} "," </if>"," <if test=\"u.name!=null and u.name.length()>0\"> "," and u.`name`=#{u.name} "," </if> ","</if> "," limit #{index},#{limit}","</script>"})public List<User> select(@Param("u") User user, @Param("index") int index, @Param("limit") int limit);
}
3、改造Example的setOrderByClause()方法,使它支持分页
利用Mapper.xml的orderByClause使用$插值的方式,进行注入分页SQL limit
UserExample user= new UserExample();
user.createCriteria().andUserIdEqualTo(1);
user.setOrderByClause("user_id asc limit 0,20");//分页功能
List<User> uList = userMapper.selectByExample(user);