SpringBoot+JPA动态分页查询

本文介绍了一个使用SpringBoot结合JPA实现的动态分页查询案例。具体包括:定义了Student实体类及扩展VO类用于封装分页参数;定义了StudentService接口及其实现类StudentServiceImpl来处理分页逻辑;并通过StudentDao接口继承JpaRepository实现数据持久层操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot+JPA动态分页查询

代码示例

1.实体类Student

@Entity
@Table(name = "tb_student")
public class Student {

	//主键
	@Id
    @Column(length = 50, nullable = false)
    private String id;

	//学生姓名
	@Column(length = 50, nullable = false)
    private String stuName;

    //创建时间
    @Column
    private Long createTime;

	//get()与set()此处省略
}

2.实体封装类StudentVO

public class StudentVO extends Student {

	//当前页
    private int page = 1;

    //页面条数(默认20)
    private int limit = 20;
    
    public StudentVO () {
    
    }
    
	public int getPage() {
        return page;
    }

	public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }
}

3.接口StudentService

public interface StudentService {
	
	Page<Student> list(StudentVO studentVO);
	
}

4.接口实现StudentServiceImpl

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
    StudentDao studentDao;

	public Page<Student> list(StudentVO studentVO) {
        PageRequest page = new PageRequest(studentVO.getPage() - 1, studentVO.getLimit(),new Sort(Sort.Direction.DESC, "createTime"));
        Page<Student> all = studentDao.findAll((root, query, builder) -> buildQueryParams(studentVO, root, builder), page);
        return all;
    }
	
	//拼装查询条件
	private Predicate buildQueryParams(StudentVO studentVO, Root<Student> root, CriteriaBuilder builder) {
        List<Predicate> list = new ArrayList<>();
        if (studentVO!= null) {
            if (StringUtils.isNotEmpty(studentVO.getStuName())) {
                list.add(builder.equal(root.get("stuName"), studentVO.getStuName()));
            }
        }
        return builder.and(list.toArray(new Predicate[]{}));
    }
}

5.持久层StudentDao

@Repository
public interface StudentDao extends JpaRepository<Student, String>, JpaSpecificationExecutor<Student> {

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值