zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

SpringDataJpa 用MySQL语句怎么分页,spring全家桶SpringDataJpa 用MySQL语句怎么分页

2023-02-18 16:35:58 时间

实体类(): 这里就略过了。。。。 数据访问接口(dao):

public interface ProblemDao extends JpaRepository<Problem,String>,JpaSpecificationExecutor<Problem>{

    @Query(value ="SELECT * FROM **" ,nativeQuery = true)//MySQL查询语句
    public Page<Problem> newlist(String labelid, Pageable pageable);//分页只需要 加上Pageable
    
   }

注意:用MySQL语句查询时,@Query(value ="语句",nativeQuery = true)中的 nativeQuery = true 必须加上,否则不生效,因为默认不是Sql语句! 控制器层(controller):

@GetMapping("/{id}/{page}/{size}")
	public Result newlist(@PathVariable String labelid,@PathVariable int page,@PathVariable int size){
		Page<Problem> pagedata = problemService.newlist(labelid, page, size);
		return new Result(true,StatusCode.OK,"查询分页成功",new PageResult<Problem>(pagedata.getTotalElements(),pagedata.getContent()));

	}

服务层(service):

public Page<Problem> newlist(String labelid, int page,int rows){
		//创建一个分页对象
		Pageable pageable=PageRequest.of(page-1,rows);
		//返回时 把分页对象返回
		return problemDao.newlist(labelid,pageable);

	}

!!!切记返回类型为: Page !!!