给老外做兼职的网站,延吉市建设厅网站,竞价排名的弊端,做网站练手项目最近在接手一个项目#xff0c;用的是JPA#xff0c;以前没使用过。在开发新的需求过程中#xff0c;发现有查询部分字段的情况#xff0c;网上逛了半天#xff0c;发现都是抄来抄去的“古文”。于是用英文搜索了下#xff0c;总结了以下几点。
版本信息#xff1a;Spr…最近在接手一个项目用的是JPA以前没使用过。在开发新的需求过程中发现有查询部分字段的情况网上逛了半天发现都是抄来抄去的“古文”。于是用英文搜索了下总结了以下几点。
版本信息Spring Boot 2.3.7
1. 不需要新建Entity但是需要一个所有部分字段的构造函数。当然如果你觉得返回的Entity中包含大量null值字段以及多一个所有部分字段的构造函数不妥也可以新建一个子集Entity。
2. 不使用findAll而是使用EntityManager来执行CriteriaQuery.multiselect的查询。
3. 没有用Query因为我的查询是动态的。
4. 也可以支持分页。
示例代码用模糊查询Merchant的部分字段并要求分页。 (不过总觉得这些代码有些冗余不知道有没有其它更优的写法
public PageMerchant listMerchant(String name, Pageable pageable) {CriteriaBuilder totalRowsCb this.entityManager.getCriteriaBuilder();CriteriaQueryLong totalRowsQuery totalRowsCb.createQuery(Long.class);RootMerchant totalRowsRoot totalRowsQuery.from(Merchant.class);totalRowsQuery.where(totalRowsCb.like(totalRowsRoot.get(name), % name %));totalRowsQuery.select(totalRowsCb.count(totalRowsRoot));Long totalRows entityManager.createQuery(totalRowsQuery).getSingleResult();CriteriaBuilder listCb this.entityManager.getCriteriaBuilder();CriteriaQueryMerchant listQuery listCb.createQuery(Merchant.class);RootMerchant listRoot listQuery.from(Merchant.class);ListOrder orderList QueryUtils.toOrders(pageable.getSort(), listRoot, listCb);listQuery .multiselect(listRoot.get(mid).alias(mid),listRoot.get(name).alias(name),listRoot.get(businessName).alias(businessName),listRoot.get(contactEmail).alias(contactEmail),listRoot.get(status).alias(status),listRoot.get(accountStatus).alias(accountStatus)).where(listCb.like(listRoot.get(name), % name %)).orderBy(orderList);ListMerchant merchantList entityManager.createQuery(listQuery).setMaxResults(pageable.getPageSize()).setFirstResult((int)pageable.getOffset()).getResultList();return new PageImpl(merchantList, pageable, totalRows);
}