LMLPHP后院

Spring Boot Jpa 使用原生 SQL 和动态分页技术

使用 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<Test, Long> {

    @Query(
            value="select * from table_name where status=:status \n#pageable\n",
            countQuery = "select count(*) from table_name where status=:status",
            nativeQuery=true)
    Page<Test> 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 分页的同学。

LMLPHP,可爱滴WEB开发框架

2017-07-27 04:30:13 1501101013 0.011014