本文主要是介绍JPA查询之Specification以及HQL、SQL查询,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、Specification
//查询条件List
List<Predicate> predicateList = new ArrayList<Predicate>();Specification specification = new Specification() {@Overridepublic Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {//root即是Join<>内部第一个泛型的类型,意思就是用SkuProduct与Picture通过SkuProduct的pictures左联Join<SkuProduct,Picture> skuProductPictureJoin = root.join("pictures",JoinType.INNER);//添加第1个查询条件:SkuProduct的code等于skuProduct.getCode(),然后将这个criteriaBuilder的条件添加到predicateListpredicateList.add(criteriaBuilder.equal(root.get("code"),skuProduct.getCode()));//添加第2个条件predicateList.add(criteriaBuilder.notEqual(skuProductPictureJoin.get("pictureType"),0));//返回return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));}
};//重要说明:Specification不支持右连接!
//Specification specification = new Specification() {
// @Override
// public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
// Join<Picture,SkuProduct> skuProductPictureJoin = root.join("pictures",JoinType.RIGHT);
// predicateList.add(criteriaBuilder.notEqual(root.get("pictureType"),0));
// predicateList.add(criteriaBuilder.equal(skuProductPictureJoin.get("code"),skuProduct.getCode()));
// return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
// }
//};List<SkuProduct> results = skuProductRepository.findAll(specification);
if(results!=null){results.stream().forEach(result->{System.out.println(result);});
}
2、HQL
@Query(value = "SELECT p FROM Picture p WHERE p.code= :code")List<Picture> findByPicture(@Param(value = "code") String code);
3、SQL
3.1--:占位符
@Query(value = "SELECT p.* FROM picture p LEFT JOIN sku_product_pictures sp_p ON p.id=sp_p.pictures_id LEFT JOIN sku_product sp ON sp_p.sku_product_id=sp.id WHERE sp.code= :code AND p.picture_type=0",nativeQuery = true)List<Picture> findBySkuProductCodeAndPicture(@Param(value = "code") String code);
3.2--?占位符
@Query(value = "SELECT p.* FROM picture p LEFT JOIN sku_product_pictures sp_p ON p.id=sp_p.pictures_id LEFT JOIN sku_product sp ON sp_p.sku_product_id=sp.id WHERE sp.code=?1 AND p.picture_type=?2",nativeQuery = true)List<Picture> findSkuProductCodeAndPicture(String code,int pictureType);
版权声明:本文为博主原创文章,未经博主允许不得转载。
这篇关于JPA查询之Specification以及HQL、SQL查询的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!