spring版
1.导包
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
2.拦截器类(需要实现Interceptor)
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import java.lang.reflect.Method;
import java.util.Properties;
public class InterceptorImp implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
System.err.println("执行到了intercept...");
Object target = invocation.getTarget();//获取当前被拦截的对象
Method method = invocation.getMethod();//被拦截的方法
Object[] args = invocation.getArgs(); //方法中的参数
//proceed:实际上执行了 method.invoke(target,args);
Object result = invocation.proceed();
/* System.err.println(result);*/
return result;
}
@Override
public Object plugin(Object o) {
return Plugin.wrap(o,this);
}
@Override
public void setProperties(Properties properties) {
}
}
3.在applicationContext.xml中配置
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--配置别名-->
<property name="typeAliasesPackage" value="cn.itsource.ssm.domain"/>
<!--注册映射文件-->
<property name="mapperLocations" value="cn.itsource.ssm.mapper.*Mapper.xml"/>
<!--配置分页拦截-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> property-key=property-value </value>
</property>
</bean>
</array>
</property>
</bean>
最后,测试
package test;
import cn.itsource.ssm.domain.User;
import cn.itsource.ssm.service.IUserService;
import cn.itsource.ssm.service.impl.UserService;
import com.github.pagehelper.PageHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
@Autowired
private IUserService service = new UserService();
@Test
public void test() throws Exception {
PageHelper.startPage(0,3);
List<User> users = service.searchAll();
System.out.println(users.size());
}
}
普通版就配置不一样,在mybatis-config.xml中配置一下就ok
<!-- 配置插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>