SpringDataJpa 分页查询
第一种方式
实体类
Student
import javax.persistence.*; import java.io.Serializable; @Entity @Table(name="Student") public class Student implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY)//自动增长主键 @Column(name = "stuid") private int stuId; @Column(name = "stuname") private String stuName; @Column(name = "stusex") private String stuSex; @Column(name = "stuage") private String stuAge; public Student(){} public Student(String stuName) { this.stuName = stuName; } public int getStuId() { return stuId; } public void setStuId(int stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this.stuSex = stuSex; } public String getStuAge() { return stuAge; } public void setStuAge(String stuAge) { this.stuAge = stuAge; } @Override public String toString() { return "Student{" + "stuId=" + stuId + ", stuName='" + stuName + '\'' + ", stuSex='" + stuSex + '\'' + ", stuAge='" + stuAge + '\'' + '}'; } }
dao
import com.oukele.demo1.oyl.entity.Student; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.QueryHints; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import javax.persistence.QueryHint; import java.util.List; import static org.hibernate.jpa.QueryHints.HINT_COMMENT; public interface StudentDao extends CrudRepository<Student, Long> { @QueryHints(value = { @QueryHint(name = HINT_COMMENT, value = "a query for pageable")}) @Query(value = " select * from student",nativeQuery = true) Page<Student> getPageList(Pageable pageable); }
测试类
@Autowired
private StudentDao studentDao;
@Test
public void getPageList(){
Pageable pageable = new PageRequest(0,3);
Page<Student> pageList = studentDao.getPageList(pageable);
for (Student student : pageList.getContent()) {
System.out.println(student);
}
}
结果
第二种方式
dao
serverImp
测试
结果
注意:测试数据 我只有 5 条 数据