本文介紹了如何使用CriteriaBuilder檢查Set中的實(shí)體是否包含某個(gè)值?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我有以下課程:
@Entity
public class Object {
@ManyToOne
@JoinColumn(name="RelationId", referencedColumnName = "ID", nullable=true)
private Relation relation;
}
@Entity
public class Relation{
@OneToMany(mappedBy="relation")
private Set<Object> objects = new HashSet<>();
@OneToMany(mappedBy="relation")
private Set<Contact> contactpersons = new HashSet<>();
}
@Entity
public class Contact{
@ManyToOne
@JoinColumn(name="RelationId")
private Relation relation;
private Boolean isPrimary;
}
這是我的rootQuery的一些代碼:
private Stream<Specification<Object>> toSpec(List<SearchCriteria> searchCriteria){
return searchCriteria.stream().map(criteria ->{
if (criteria.isSet(ObjectKeys.searchObject)) {
return (Specification<Object>) (root, query, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
[Here a criteriabuilder predicate needs to go that check if object has relation that has
contacts that have isPrimary on true]
return criteriaBuilder.or(predicates.toArray(new Predicate[0]));
}
}
}
}
如何使用CriteriaBuilder檢查對(duì)象關(guān)系是否包含isPrimary
on true的聯(lián)系人
我嘗試使用criteriaBuilder.in()
,但它只能檢查聯(lián)系人對(duì)象是否在集合中,而不能檢查聯(lián)系人對(duì)象是否具有特定值。我也嘗試過(guò)使用聯(lián)接,但這并沒(méi)有給出正確的結(jié)果,因?yàn)槲抑荒苁褂米?、?nèi)或右聯(lián)接,這會(huì)導(dǎo)致重復(fù)的對(duì)象或不可為空的對(duì)象。
SQLJPA
您在這里需要的是關(guān)系代數(shù)中的所謂半聯(lián)接,它是通過(guò)推薦答案中的EXISTS謂詞建模的,在JPA中也受支持。您必須將相關(guān)子查詢與EXISTS謂詞一起使用。大致如下:
private Stream<Specification<Object>> toSpec(List<SearchCriteria> searchCriteria){
return searchCriteria.stream().map(criteria ->{
if (criteria.isSet(ObjectKeys.searchObject)) {
return (Specification<Object>) (root, query, criteriaBuilder) -> {
Subquery<Integer> subquery = query.subquery(Integer.class);
Root<Object> correlated = subquery.correlate(root);
Join<?, ?> join = correlated.join("relation").join("contactpersons");
subquery.select(criteriaBuilder.literal(1));
subquery.where(criteriaBuilder.isTrue(join.get("isPrimary")));
return criteriaBuilder.exists(subquery);
}
}
}
}
這篇關(guān)于如何使用CriteriaBuilder檢查Set中的實(shí)體是否包含某個(gè)值?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,