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<Person, Integer>{
}
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<Person> findAll() {
Iterable<Person> persons = personDao.findAll();
return persons;
}
1.2.5. 分页查询
public Iterable<Person> findAll(Pageable pageable) {
Page<Person> 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<Person> findAll();
Iterable<Person> 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<Person> findAll() {
Iterable<Person> persons = personDao.findAll();
return persons;
}
public Iterable<Person> findAll(Pageable pageable) {
Page<Person> persons = personDao.findAll(pageable);
return persons;
}
}