jpa 分页查询

本文介绍了使用Java Persistence API (JPA)进行分页查询的五种方法,包括本地SQL查询、已实现的分页接口、Query注解、扩充findAll方法及使用entityManager,每种方法都有详细的代码示例。

转自https://www.cnblogs.com/hdwang/p/7843405.html

法一(本地sql查询,注意表名啥的都用数据库中的名称,适用于特定数据库的查询)

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
    nativeQuery = true)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

法二(jpa已经实现的分页接口,适用于简单的分页查询)

public interface PagingAndSortingRepository<T, ID extends Serializable>
  extends CrudRepository<T, ID> {

  Iterable<T> findAll(Sort sort);

  Page<T> findAll(Pageable pageable);
}

Accessing the second page of User by a page size of 20 you could simply do something like this:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));
User findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

Slice<User> findTop3ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);

//service
 Sort sort = new Sort(Sort.Direction.DESC,"createTime"); //创建时间降序排序
 Pageable pageable = new PageRequest(pageNumber,pageSize,sort);
 this.depositRecordRepository.findAllByUserIdIn(userIds,pageable);

//repository
Page<DepositRecord> findAllByUserIdIn(List<Long> userIds,Pageable pageable);

法三(Query注解,hql语局,适用于查询指定条件的数据)

 @Query(value = "select b.roomUid from RoomBoard b where b.userId=:userId and b.lastBoard=true order by  b.createTime desc")
    Page<String> findRoomUidsByUserIdPageable(@Param("userId") long userId, Pageable pageable);
	
	
	Pageable pageable = new PageRequest(pageNumber,pageSize);
Page<String> page = this.roomBoardRepository.findRoomUidsByUserIdPageable(userId,pageable);
List<String> roomUids = page.getContent();
//可以自定义整个实体(Page<User>),也可以查询某几个字段(Page<Object[]>),和原生sql几乎一样灵活。

法四(扩充findAll,适用于动态sql查询)


public interface UserRepository extends JpaRepository<User, Long> {

    Page<User> findAll(Specification<User> spec, Pageable pageable);
} 

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> getUsersPage(PageParam pageParam, String nickName) {
        //规格定义
        Specification<User> specification = new Specification<User>() {

            /**
             * 构造断言
             * @param root 实体对象引用
             * @param query 规则查询对象
             * @param cb 规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>(); //所有的断言
                if(StringUtils.isNotBlank(nickName)){ //添加断言
                    Predicate likeNickName = cb.like(root.get("nickName").as(String.class),nickName+"%");
                    predicates.add(likeNickName);
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };
        //分页信息
        Pageable pageable = new PageRequest(pageParam.getPage()-1,pageParam.getLimit()); //页码:前端从1开始,jpa从0开始,做个转换
        //查询
        return this.userRepository.findAll(specification,pageable);
    }

}

法五(使用entityManager,适用于动态sql查询)

@Service
@Transactional
public class IncomeService{

    /**
     * 实体管理对象
     */
    @PersistenceContext
    EntityManager entityManager;

    public Page<IncomeDaily> findIncomeDailysByPage(PageParam pageParam, String cpId, String appId, Date start, Date end, String sp) {
        StringBuilder countSelectSql = new StringBuilder();
        countSelectSql.append("select count(*) from IncomeDaily po where 1=1 ");

        StringBuilder selectSql = new StringBuilder();
        selectSql.append("from IncomeDaily po where 1=1 ");

        Map<String,Object> params = new HashMap<>();
        StringBuilder whereSql = new StringBuilder();
        if(StringUtils.isNotBlank(cpId)){
            whereSql.append(" and cpId=:cpId ");
            params.put("cpId",cpId);
        }
        if(StringUtils.isNotBlank(appId)){
            whereSql.append(" and appId=:appId ");
            params.put("appId",appId);
        }
        if(StringUtils.isNotBlank(sp)){
            whereSql.append(" and sp=:sp ");
            params.put("sp",sp);
        }
        if (start == null)
        {
            start = DateUtil.getStartOfDate(new Date());
        }
        whereSql.append(" and po.bizDate >= :startTime");
        params.put("startTime", start);

        if (end != null)
        {
            whereSql.append(" and po.bizDate <= :endTime");
            params.put("endTime", end);
        }

        String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString();
        Query countQuery = this.entityManager.createQuery(countSql,Long.class);
        this.setParameters(countQuery,params);
        Long count = (Long) countQuery.getSingleResult();

        String querySql = new StringBuilder().append(selectSql).append(whereSql).toString();
        Query query = this.entityManager.createQuery(querySql,IncomeDaily.class);
        this.setParameters(query,params);
        if(pageParam != null){ //分页
            query.setFirstResult(pageParam.getStart());
            query.setMaxResults(pageParam.getLength());
        }

        List<IncomeDaily> incomeDailyList = query.getResultList();
      if(pageParam != null) { //分页
            Pageable pageable = new PageRequest(pageParam.getPage(), pageParam.getLength());
            Page<IncomeDaily> incomeDailyPage = new PageImpl<IncomeDaily>(incomeDailyList, pageable, count);
            return incomeDailyPage;
        }else{ //不分页
            return new PageImpl<IncomeDaily>(incomeDailyList);
        }
    }

    /**
     * 给hql参数设置值
     * @param query 查询
     * @param params 参数
     */
    private void setParameters(Query query,Map<String,Object> params){
        for(Map.Entry<String,Object> entry:params.entrySet()){
            query.setParameter(entry.getKey(),entry.getValue());
        }
    }
}

JPA分页查询可通过`JpaSpecificationExecutor`的`Page findAll(Specification spec, Pageable pageable)`方法按照指定的规格条件实现分页查询[^1]。以下为使用方法和示例代码: ### 使用方法 1. **添加依赖**:在`pom.xml`文件中添加Spring Data JPA的依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. **定义实体类**:创建一个与数据库表对应的实体类。 ```java import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int age; // 构造函数、getter和setter方法 public User() {} public User(String name, int age) { this.name = name; this.age = age; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 3. **创建Repository接口**:继承`JpaRepository`和`JpaSpecificationExecutor`接口。 ```java import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> { } ``` 4. **实现分页查询**:在服务类中使用`Pageable`对象进行分页查询。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; @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); } } ``` 5. **调用分页查询方法**:在控制器中调用服务类的方法。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public Page<User> getUsers(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { return userService.getUsersByPage(page, size); } } ``` ### 示例代码解释 - **`PageRequest.of(page, size)`**:创建一个`Pageable`对象,指定页码和每页的记录数。 - **`userRepository.findAll(pageable)`**:调用`JpaRepository`的`findAll`方法进行分页查询。 - **`Page<User>`**:返回一个`Page`对象,包含分页查询的结果。 如果还不知道Spring Boot怎么使用JPA,可参考[Springboot快速整合JPA实现增删查改](https://blog.csdn.net/qq_35387940/article/details/102541311) [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值