php 原生sql 分页查询,Spring Boot Jpa 使用原生 SQL 和动态分页

本文介绍了如何在Spring Data JPA中使用原生SQL进行分页查询,通过示例代码展示了在`TestRepository`接口中定义带有动态排序和分页的查询方法,并给出了对应的实体类`Test`。遇到Jpa分页查询问题的同学可以参考此教程。
摘要由CSDN通过智能技术生成

使用 Jpa 分页报个错:

Cannot use native queries with dynamic sorting and/or pagination in method public abstract org.springframework.data.domain.Page

Jpa 的原生 SQL 对命名没有严格的要求,如下示例:package com.lmlphp.test;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.jpa.repository.Modifying;

import org.springframework.transaction.annotation.Transactional;

import org.springframework.data.repository.query.Param;

import org.springframework.data.domain.Page;

import org.springframework.data.domain.Pageable;

public interface TestRepository extends JpaRepository {

@Query(

value="select * from table_name where status=:status \n#pageable\n",

countQuery = "select count(*) from table_name where status=:status",

nativeQuery=true)

Page findByStatus(@Param("status") int status, Pageable pageable);

}

Entity 示例:package com.lmlphp.test;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import java.io.Serializable;

@Entity

@Table(name="table_name")

public class Test implements Serializable{

@Id

@GeneratedValue

private Long id;

private int status;

public Long getId(){

return id;

}

public int getStatus(){

return status;

}

public Test(){}

public Test(int status){

this.status = status;

}

public String toString(){

return String.format("id=%s, status='%s'", id, status);

}

}

希望能帮助不会使用 Jpa 原生 SQL 分页的同学。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值