spring分页

依赖架包

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.0.4</version>
		</dependency>

mybatis-config.xml配置分页插件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration 
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
     <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->        
        </plugin>
    </plugins>
</configuration>

测试一下

@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class TUser2MapperTest extends AbstractTestNGSpringContextTests{

	@Autowired
	TUser2Mapper usermapper;
	
  @Test
  public void countByExampleTest() {
	  TUser2Example example =new TUser2Example();
	  Criteria cri = example.createCriteria();
	  cri.andAgeBetween(1, 100);
	  cri.andAgeLessThan(1000);
	  Criteria cri2= example.createCriteria();
	  cri2.andUserNameNotLike("zhangsan%");
	  example.or(cri2);
	//设置当前第几页,每页取几条数据
	  PageHelper.startPage(2, 2);
	  //usermapper.countByExample(example);
	  List<TUser2> list = usermapper.selectByExample(example);
	  PageInfo<TUser2> pageInfo=new PageInfo<>(list);
	  //获得当前页有几条数据
	  System.out.println(pageInfo.getPageNum());
  }
 }
Spring中进行分页查询可以使用Spring Data JPA或者MyBatis-Plus等框架提供的分页功能。 使用Spring Data JPA进行分页查询的步骤如下: 1. 在你的实体类对应的Repository接口中继承`org.springframework.data.repository.PagingAndSortingRepository`接口或者`org.springframework.data.jpa.repository.JpaRepository`接口。 2. 在你的Service类中注入该Repository。 3. 在Service类中使用`Pageable`对象来指定分页参数,例如页码、每页数据条数等。 4. 调用Repository的分页查询方法,传入`Pageable`对象作为参数,获取到分页结果。 下面是一个使用Spring Data JPA进行分页查询的示例代码: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public Page<User> getUsersByPage(int page, int size) { Pageable pageable = PageRequest.of(page, size); return userRepository.findAll(pageable); } } ``` 在上面的示例中,我们在UserService中注入了UserRepository,并定义了一个方法`getUsersByPage`来实现分页查询。通过调用`userRepository.findAll(pageable)`方法来执行分页查询,并将结果封装在`Page`对象中返回。 除了Spring Data JPA,如果你使用MyBatis-Plus框架,它也提供了方便的分页查询功能。你可以使用`com.baomidou.mybatisplus.extension.plugins.pagination.Page`对象来设置分页参数,并通过调用MyBatis-Plus的分页查询方法来获取分页结果。 希望以上信息对你有帮助!如果还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值