spring data jpa中的page分页

  1. SceneryComment实体类
@Data
@Entity
@Table(name = 表名)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SceneryComment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer id;
   
    private Integer sceneryId;
    
    private String comment;
   
    private String picture;
   
    private Integer score;
  
    private Integer userId;

    private Date createData;

    @Transient
    private UserComment userComments = new UserComment();
  1. UserComment实体类
@Data
public class UserComment {

    private Integer id=1;

    private String headPortrait="http://pic37.nipic.com/20140113/8800276_184927469000_2.png";

    private String userName="张三";

}
  1. Repository类
/**
     * 根据userid查所有数据
     * @param userId
     * @return
     */
    Page findBySceneryIdAndUserId(Integer sceneryId,Integer userId,Pageable pageable);
  1. Service类(page一定要从0开始,默认是1,如果不减1的话,第一页的数据就显示不出来)
public Page findUid(Integer sceneryId,Integer uid,Integer page, Integer size){
        Pageable pageable = PageRequest.of(page-1,size,new Sort(Sort.Direction.DESC, "createData"));
        return sceneryCommentRepository.findBySceneryIdAndUserId(sceneryId,uid,pageable);
    }
  1. Controller类
    @GetMapping("user")
    public BaseResponse findByUid(@RequestParam("sceneryId") Integer sceneryId,
                                  @RequestParam(value = "userId")Integer userId,
                                  @RequestParam(value = "page",defaultValue = "1")Integer page,
                                  @RequestParam(value = "size",defaultValue = "20")Integer size) {
        BaseResponse baseResponse = BaseResponse.initialize();
        Page result=sceneryCommentService.findUid(sceneryId,userId, page, size);
        baseResponse.setTotalCount(result.getTotalElements());
        baseResponse.setResult(result.getContent());
        return baseResponse;
    }
  1. BaseResponse类
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@AllArgsConstructor
@NoArgsConstructor
public class BaseResponse {

    private Integer code;
    private String msg;
    private Long totalCount;
    private Object result;
    
    public static BaseResponse initialize(){
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(0);
        baseResponse.setMsg("successfully");
        return baseResponse;
    }
    
}
  1. 测试
    spring data jpa中的page分页_第1张图片
    说明:使用了springboot,在用Data注解时要用lombok

你可能感兴趣的:(SpringCloud)