spring data jpa 分页配置 及简单示例

时间:2020-12-11 20:34:07

dao层:

public interface CompetitorGoodRepository extends PagingAndSortingRepository<Good,Long>,JpaSpecificationExecutor{
}

service层:

   @Service
public class CompetitorServiceImpl{

@Autowired
private CompetitorGoodRepository competitorGoodRepository;
@Override
public Page<Good> findCompetitorList(int page, int size, Long userId) {
this.userId=userId;
PageRequest pageRequest=this.buildPageRequest(page,size);
Page<Good> goodPageList=this.competitorGoodRepository.findAll(new MySpec(),pageRequest);
return goodPageList;
}

private PageRequest buildPageRequest(int page,int size){
Sort sort=new Sort(Sort.Direction.ASC,"goodId");
return new PageRequest(page,size);
}

//多对多的配置(对应关系借助中间表,且中间表不止外键属性,还有其他属性)
private class MySpec implements Specification<Good>{
@Override
public Predicate toPredicate(Root<Good> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

SetJoin<Good, UserGood> userUserGoodJoin=root.join(root.getModel().getSet("userGoodSet",UserGood.class),JoinType.INNER);
Predicate p2=cb.equal(userUserGoodJoin.get("user").get("userId").as(Long.class),userId);
cq.where(p2);
return null;
}
}
}

uer表 主键user_id, good表主键good_id, 对应中间表user_good,外键是good_id,user_id
user 对good是多对多
spring data jpa 分页配置 及简单示例

/*Join