这篇文章讲一下数据分页。
注:文章中涉及到的数据库为Oracle。
1.正文
我们继续以上一篇文章的TEST_TABLE_01为例。
@Entity
@Data
@Table(name = "TEST_TABLE_01", schema = "LOCAL")
public class Table01Entity {
@Id
private long id;
private String fileType;
private String fileSize;
private String fileName;
}
定义Repo类,要想实现分页,需要注意几点,
1.在@Query里除了指定value,也就是sql代码,还要新增一个参数countQuery,内容把sql拷贝下来,改成查询count就好了;
2.返回值改为Page;
3.新增Pageable入参。
Pageable pageable = PageRequest.of(pageNumber,pageSize);
public interface Table01Repository extends JpaRepository<Table01Entity, Long>, JpaSpecificationExecutor {
@Query(value = "select * from TEST_TABLE_01 t1" +
"where t1.file_type='01'",
countQuery = "select count(0) from TEST_TABLE_01 t1"+
"where t1.file_type='01'",nativeQuery = true)
public Page<Map> findByIdOnYourOwn(Pageable pageable);
}
执行一下,你会发现,返回值就变成了带有分页的数据结构了。
但是有一个问题,返回值的key都变成了大写,FILE_TYPE,FILE_SIZE,FILE_NAME,我们需要改成如下,就好了(注意是双引号,再加一个转义字符)。
public interface Table01Repository extends JpaRepository<Table01Entity, Long>, JpaSpecificationExecutor {
@Query(value = "select id as \"id\", file_type as \"fileType\", file_size as \"fileSize\", file_name as \"fileName\" from TEST_TABLE_01 t1" +
"where t1.file_type='01'",
countQuery = "select count(0) from TEST_TABLE_01 t1"+
"where t1.file_type='01'",nativeQuery = true)
public Page<Map> findByIdOnYourOwn(Pageable pageable);
}