mybatis实现分页

实现分页实质上就是截取查询结果,仍是先贴代码,再来分析sql

下面是mapper.xml里面的配置数据库

<select id="queryRoleByPage" resultMap="roleCustomeMap">
        select
            a.role_id,a.role_name,a.available ,
            b.permission_id,
            c.permission_name
            from sys_role a, sys_role_permission b, sys_permission c
            where a.role_id = b.role_id and b.permission_id = c.permission_id and a.role_id in (
            select top ${rows} role_id from sys_role where role_id in(
            select top ${pagebegin} role_id from sys_role order by role_id asc
              )order by role_id desc
)order by a.role_id asc </select>

在mapper中接口的配置apache

  public List<SysRoleCustome> queryRoleByPage(@Param("pagebegin")int pagebegin,@Param("rows")int rows);

先说说mapper接口的配置,这里须要加上@Param这个制定参数名称,不然会出现,当使用多个参数时,必须制定,一个参数能够不指定mybatis

nested exception is org.apache.ibatis.binding.BindingException: Parameter 'rows' not found

这样的错误app

接着看mapper.xml的配置,咱们知道,获取mapper接口给的值的时候,咱们用的是#{value},可是在这里,我先使用了这个,而后就出现这样的错误:sqlserver

 Cause: com.microsoft.sqlserver.jdbc.SQLServerException: '$@P0' 附近有语法错误。

致使这个错误的缘由是什么呢?spa

错误解释以下: 
在Java中对数据库查询时常常使用“Select Top ? * From 表名 Where 列名 = ?”的SQL语句,此时的问号是PreparedStatement预编译对象的参数占位符,须要使用setXX()系列方法对其赋值后再执行。可是,Top后面是不容许使用问号占位符的,此处的错误就是由此引发的。

按照上面的解释,若是咱们用#来赋值的话,那就是预编译为“?”的,而这个致使了上面的错误,那么怎么解决呢?有两种方式.net

1,用$来赋值,其实就是将值写入语句中,并无预编译,如最上面用红色加粗的那样code

2,直接拼接字符串,效果和上面是同样的,原理是同样的,这个能够用在存储过程当中server

我是按照下面的文章找的第四种方法,关键就是结合mybatis来实现的一些细节,不注意,则会出现错误

高效的SQLSERVER分页查询(推荐)

相关文章
相关标签/搜索