PageAndSort java_jpa之PagingAndSortingRepository带分页查询 | 学步园

本文介绍了如何在Spring整合JPA的环境中使用PagingAndSortingRepository进行分页查询。通过继承该接口,可以方便地实现新增、删除、修改和查询操作。特别是分页查询,只需指定Pageable接口的页数和每页大小,即可实现高效的数据分页展示。
摘要由CSDN通过智能技术生成

此篇文章建立在spring整合jpa环境的基础上,不会的请看前几篇文章.

1.1.  Dao接口继承PagingAndSortingRepository接口

PersonDao.java

package com.morris.dao.inter;

import org.springframework.data.repository.PagingAndSortingRepository;

import com.morris.entity.Person;

public interface PersonDao extends PagingAndSortingRepository{

}

1.2.  使用PagingAndSortingRepository接口的方法

1.2.1.  新增

public void save(Person person) {

personDao.save(person);

}

1.2.2.  删除

public void delete(Person person) {

personDao.delete(person);

}

public void delete(Integer id) {

personDao.delete(id);

}

1.2.3.  修改

public void update(Person person) {

personDao.save(person);

}

1.2.4.  查询

public Person findById(Integer id) {

Person person = personDao.findOne(id);

return person;

}

public Iterable findAll() {

Iterable persons = personDao.findAll();

return persons;

}

1.2.5.  分页查询

public Iterable findAll(Pageable pageable) {

Page persons = personDao.findAll(pageable);

return persons;

}

其中Pageable是一个接口,具体的实现类为PageRequest,下面为PageRequest的一个构造方法

public PageRequest(int page, int size)

{

this(page, size, null);

}

只需要指定分页时页数和每页的大小即可.

1.3.  源代码

IPersonService

package com.morris.service.inter;

import org.springframework.data.domain.Pageable;

import com.morris.entity.Person;

public interface IPersonService {

void save(Person person);

void delete(Person person);

void delete(Integer id);

void update(Person person);

Person findById(Integer id);

Iterable findAll();

Iterable findAll(Pageable pageable);

}

PersonServiceImpl.java

package com.morris.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;

import org.springframework.data.domain.Pageable;

import org.springframework.stereotype.Service;

import com.morris.dao.inter.PersonDao;

import com.morris.entity.Person;

import com.morris.service.inter.IPersonService;

@Service("personService")

public class PersonServiceImpl implements IPersonService {

@Autowired

private PersonDao personDao;

public void save(Person person) {

personDao.save(person);

}

public void delete(Person person) {

personDao.delete(person);

}

public void delete(Integer id) {

personDao.delete(id);

}

public void update(Person person) {

personDao.save(person);

}

public Person findById(Integer id) {

Person person = personDao.findOne(id);

return person;

}

public Iterable findAll() {

Iterable persons = personDao.findAll();

return persons;

}

public Iterable findAll(Pageable pageable) {

Page persons = personDao.findAll(pageable);

return persons;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值