Java 如何创建通用(类型和属性)Spring Jpa规范
目前我正在使用SpringDataJPA和CriteriaAPI。我为一个实体创建了一个自定义存储库。谓词是通过以下方式创建的:2个示例:Java 如何创建通用(类型和属性)Spring Jpa规范,java,spring,jpa,spring-data-jpa,Java,Spring,Jpa,Spring Data Jpa,目前我正在使用SpringDataJPA和CriteriaAPI。我为一个实体创建了一个自定义存储库。谓词是通过以下方式创建的:2个示例: public static <E> Predicate matchingCountryOrGroup(CountryCode country, List<String> euGroups, SingularAttribute<E, String> countryAttribute, SetA
public static <E> Predicate matchingCountryOrGroup(CountryCode country, List<String> euGroups,
SingularAttribute<E, String> countryAttribute,
SetAttribute<E, String> countryGroupAttribute, Root<E> deliveryMode,
CriteriaBuilder cb) {
String countryGroup = country.getCountryGroup();
Predicate countryGroupMatchPredicate = matchCountryGroup(countryGroup, euGroups, countryGroupAttribute, cb, deliveryMode);
Predicate countryMatchPredicate = caseInsensitiveStringMatch(country.getCountryId(), countryAttribute, cb,
deliveryMode);
Predicate countryPredicate = cb.or(countryGroupMatchPredicate, countryMatchPredicate);
Predicate bothNull = cb.and(cb.isNull(deliveryMode.get(countryAttribute)),
cb.isEmpty(deliveryMode.get(countryGroupAttribute)));
return cb.or(countryPredicate, bothNull);
}
public static <E> Predicate caseInsensitiveStringMatch(String match,
SingularAttribute<E, String> stringAttribute, CriteriaBuilder cb,
Root<E> deliveryMode) {
return cb.equal(cb.lower(deliveryMode.get(stringAttribute)), match.toLowerCase());
}
公共静态谓词匹配CountryOrGroup(CountryCode国家,列出euGroups,
单数属性countryAttribute,
SetAttribute countryGroupAttribute,根deliveryMode,
标准生成器(cb){
字符串countryGroup=country.getCountryGroup();
谓词countryGroupMatchPredicate=matchCountryGroup(countryGroup、euGroups、countryGroupAttribute、cb、deliveryMode);
谓词countryMatchPredicate=caseInsensitiveStringMatch(country.getCountryId(),countryAttribute,cb,
配送模式);
谓词countryPredicate=cb.or(countryGroupMatchPredicate,countryMatchPredicate);
谓词bothNull=cb.and(cb.isNull(deliveryMode.get(countryAttribute)),
cb.isEmpty(deliveryMode.get(countryGroupAttribute));
返回cb.or(countryPredicate,bothNull);
}
公共静态谓词caseInsensitiveStringMatch(字符串匹配,
SingularAttribute stringAttribute、CriteriaBuilder cb、,
根交付模式){
返回cb.equal(cb.lower(deliveryMode.get(stringAttribute)),match.toLowerCase();
}
我在针对不同属性的多个查询中使用这些谓词,因此属性和不同实体的参数也是如此。
真正令人恼火的是,我总是必须输入CriteriaBuilder和Root
另一方面,我看到了Spring规范API,通过注入正确的根和CriteriaBuilder,它似乎正好解决了这个问题
问题是:我如何利用/使用这个规范API和我的谓词类型——不同实体的泛型和不同属性的泛型
更新了问题和代码以增加清晰度这里似乎有多个问题:标题中的问题和您似乎已经回答过的最后一句话,以及关于删除
规范参数的问题。请通过删除另一个来澄清您的问题。我想删除方法签名中的这些JPA标准API参数。规范API正是有帮助的,但如何以通用的方式使用它们呢?对不起,这听起来像是你重复了这两个问题。什么意思?我经常重复这个问题。一次在标题中,一次在正文末尾?问题还不清楚吗?正确。我还不清楚。我仍然看到两个截然不同的问题。