Springboot+hibernate+jpa的方法使用,分页
现在我们做的项目中,有一些是使用springboot+hibernate+jpa的框架,这种框架组成还是有很多灵活性的,虽然我之前都是用mybatis,对于一些中小型的项目还是比较适用的,springboot的简化配置,约定大于配置,使用jpa,大大提高代码的灵活性,我这边写了一个简单的案例。列一个接口:
1.实体类
2.dao
3.service
4.service的实现类
咱们来根据具体的方法,列出写法
列一个分页的接口,如下:
// 租客列表 // 分页查询
default Page<ShareOpenDoor> actList1(ShareOpenDoor con, Pageable pageable) {
EntityManager em = SpringUtils.getBean(EntityManager.class);
Map<String, Object> params = new HashMap<>();
StringBuffer jpql = new StringBuffer(" select * from hotel_share_opendoor_info fa where deleted=false ");
if (con.getHotel() != null && con.getHotel().getId() != 0) {
jpql.append(" and fa.hotel_id = :hotelId ");
params.put("hotelId", con.getHotel().getId());
}
if(con.getDostatus()!=null) {
if (con.getDostatus() == 0) {
jpql.append(" and fa.dostatus =0 ");
} else if (con.getDostatus() == 2) {
jpql.append(" and fa.dostatus =2 ");
} //
params.put("dostatus", con.getDostatus() );
} //
if(con.getRoomNo()!=0){ //
jpql.append(" and fa.room_no = :roomNo "); //
params.put("roomNo", con.getRoomNo() ); //
}
if (StringUtils.isNotBlank(con.getRoomNo())) {
jpql.append(" and fa.room_no = :roomNo ");
params.put("roomNo", con.getRoomNo());
}
if(con.getCheckoutType()!= null ) {
if(con.getCheckoutType()==0) {
jpql.append(" and fa.checkout_type= :checkoutType");
params.put("checkoutType", 0);
}
if(con.getCheckoutType()==1) {
jpql.append(" and fa.checkout_type= :checkoutType");
params.put("checkoutType", 1);
}}
if (pageable.getSort() != null) {
Iterator<Sort.Order> is = pageable.getSort().iterator();
jpql.append(" order by ");
while (is.hasNext()) {
Sort.Order e = is.next();
jpql.append(e.getProperty()).append(" ").append(e.getDirection());
} }
String countSql = "SELECT count(1) FROM (" + jpql + ") jpqlcount";
Query query = em.createNativeQuery(jpql.toString(), ShareOpenDoor.class);
Query count = em.createNativeQuery(countSql.toString());
for (String key : params.keySet()) {
query.setParameter(key, params.get(key));
count.setParameter(key, params.get(key));
}
query.setFirstResult(pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
List<ShareOpenDoor> list = query.getResultList();
BigInteger total = (BigInteger) count.getSingleResult();
Page<ShareOpenDoor> page = new PageImpl<>(list, pageable, total.longValue());
return page;
}// ...
这个方法利用jpa的自带的分页的插件,传入的路径要加入pag 页码,rows行数
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统