本文介绍了规范中的JpaSpecificationExecutor JOIN + ORDER BY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个使用JOIN和ORDER BY的查询,想要使用Criteria Api在我的存储库中使用它。I have a query using a JOIN and ORDER BY and want to use it within my repository using the Criteria Api.在这里我发现,如何包装这样的查询CriteriaQuery(链接)。Here I found, how to wrap such a query into a CriteriaQuery (Link).CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);Root<Pet> pet = cq.from(Pet.class);Join<Pet, Owner> owner = cq.join(Pet_.owners);cq.select(pet);cq.orderBy(cb.asc(owner.get(Owner_.lastName),owner.get(Owner_.firstName)));另一方面,我发现一些例子将Criteria Api与JpaRepository结合使用(示例)。On the other side, I found some examples to use the Criteria Api in Combination with a JpaRepository (example).问题是存储库中的所有方法都需要一个规范:The Problem is that all methods in the repository expect a Specification:T findOne(Specification<T> spec);总是这样构建:public static Specification<PerfTest> statusSetEqual(final Status... statuses) { return new Specification<PerfTest>() { @Override public Predicate toPredicate(Root<PerfTest> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.not(root.get("status").in((Object[]) statuses)); } };}所以在一方面我知道如何创建CriteriaQuery,另一方面,我需要一个基于谓词构建的规范,我无法弄清楚如何将CriteriaQuery解析为规范/谓词。So at one side I know how to create a CriteriaQuery, and on the other side I need a Specification which is build from a Predicate, and I can not figure out how to parse the CriteriaQuery into a Specification/Predicate.推荐答案尝试这样的事情(我假设宠物有很多所有者):Try something like this (I assumed pet has many owners):public static Specification<Pet> ownerNameEqual(String ownerName) { return new Specification<Pet>() { @Override public Predicate toPredicate(Root<Pet> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { Join<Pet, Owner> owners = root.join("owners"); criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id"))); return criteriaBuilder.equal(owners.get("name"), ownerName); } }; }这只是搜索至少一位拥有者姓名的所有宠物的示例等于 ownerNameThis is just an example to search all pets whose at least one owner has name equal to ownerName但是你可以添加一个方法 List< Pet> findByOwnersNameOrderByIdDesc(String ownerName); 在您的存储库中(相当于规范)。But you could add a method List<Pet> findByOwnersNameOrderByIdDesc(String ownerName); in your repository instead (as an equivalent to Specification). 这篇关于规范中的JpaSpecificationExecutor JOIN + ORDER BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-13 04:05